Why is for() less efficient than foreach?
biozic via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Feb 10 04:57:38 PST 2017
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];
}
```
You can also do:
```
d = a[] * b[] / c[];
```
with no loop statement at all.
More information about the Digitalmars-d-learn
mailing list