Performance penalty for using ranges
Joseph Rushton Wakeling
joseph.wakeling at webdrake.net
Sun Aug 25 13:42:41 PDT 2013
On 25/08/13 22:22, bearophile wrote:
> In short all your variables/function arguments should be tagged as
> const/immutable unless the semantics of your algorithm needs them to mutate, or
> unless some limit in D/Phobos forbids you to (like when you have created a lazy
> range, currently you can't assign it to const and then use it).
It's slightly annoying that one can't readily get immutability to play nice with
more general iterations than i .. j.
For example if you consider the loop,
for (i = 10; i > 0; --i) { ... }
You can't make i immutable for obvious reasons but it's not clear to me how you
can get a performant version of that with immutable i.
You could do something like [*],
foreach (immutable i; iota(1, 11).retro) { ... }
... but that will be slow and inefficient.
Ditto for cases like
for (i = 0; i < n; i += 2) { ... }
which you could write as
foreach (immutable i; iota(0, n, 2)) { ... }
... but again, that will be slow compared to the for loop or a foreach across an
interval.
[* Hijacking of discussion: a while back I think I floated the idea of
generalizing iota() with closed/open boundary conditions similar to those found
in std.random.uniform; so e.g. you could do iota!"[]"(0, 10) and the upper bound
would be included in the values returned. Would be useful for cases like these.]
More information about the Digitalmars-d
mailing list