Ranges seem awkward to work with

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Sep 12 09:42:57 PDT 2017


On Tuesday, September 12, 2017 13:47:47 Azi Hassan via Digitalmars-d-learn 
wrote:
> On Tuesday, 12 September 2017 at 01:13:29 UTC, Hasen Judy wrote:
> > Now, a lot of library functions seem to expect ranges as inputs
> > and return ranges as output.
>
> Unless I'm mistaken, it was done on purpose to reduce the amount
> of memory allocations in the standard library so that it becomes
> @nogc-friendly. But yes, you can use std.array.array to turn it
> into an array, but keep in mind that it does allocate so you
> might need to watch out if you're dealing with large CSV files.

Ranges were a big thing in Phobos years before @nogc came along. They're
used because they're an extremely powerful idiom. I don't even recall much
in the way of discussions related to their efficiency vs arrays early on.
That did come later, and ranges have significantly helped the memory
efficiency of D programs regardless of @nogc, but that really wasn't the
motivating factor. And even now, a lot of the basic uses of ranges _do_
allocate, because they use lambdas that end up with closures being allocated
for them (which uses far less memory than allocating a dynamic array but is
not @nogc). That can be avoided by doing stuff like using static nested
functions or functors, but your average rangd-based code doesn't tend to
jump through those hoops.

Ranges do take some getting used to, but we have them precisely because
they're so flexible and powerful.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list