Loops versus ranges

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Dec 19 05:07:36 PST 2014


On Fri, 19 Dec 2014 12:20:34 +0000
bearophile via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com>
wrote:

> anon:
> 
> > Changed to
> >     return data.map!(n => foo2(data, i + 1, 
> > max)).cache.joiner.array;
> > then it produced the same result as array version. 
> > `map.cache.join` resulted in 597871.
> 
> This is close to tell what the cause is :-)

easy deal indeed: this is due to how `.save` done in lazy mapped range,
plus some range properties.

as source range for mapping is forward range (i.e. indicating that it
has `.save`), `.join` assumes that `.save` is cheap and goes by the
route where it iterates the range twice: first calculating range length
and then generating values for preallocated array. but `.save` is not
cheap in our case, so `.join` is effectively calculating EVERYTHING
TWICE. oops. and as we have no memoization here, the number of calls is
exploding.

thank you for the riddle, it took me some time to see what's going on
here. ;-)
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20141219/add7dd75/attachment.sig>


More information about the Digitalmars-d-learn mailing list