Why is for() less efficient than foreach?
Bastiaan Veelo via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Feb 10 05:32:37 PST 2017
On Friday, 10 February 2017 at 12:57:38 UTC, biozic wrote:
> On Friday, 10 February 2017 at 12:39:50 UTC, Bastiaan Veelo
> wrote:
>> void foreach_loop()
>> {
>> foreach(n, elem; d[])
>> elem = a[n] * b[n] / c[n];
>> }
>
> It's fast because the result of the operation (elem) is
> discarded on each iteration, so it is probably optimized away.
> Try:
> ```
> void foreach_loop()
> {
> foreach(n, ref elem; d[])
> elem = a[n] * b[n] / c[n];
> }
> ```
Hah, of course.
> You can also do:
> ```
> d = a[] * b[] / c[];
> ```
> with no loop statement at all.
Nice.
Thanks.
More information about the Digitalmars-d-learn
mailing list