Why is for() less efficient than foreach?
Stefan Koch via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Feb 10 04:58:19 PST 2017
On Friday, 10 February 2017 at 12:39:50 UTC, Bastiaan Veelo wrote:
> Benchmarking for() against foreach():
>
> /////////
> enum size_t maxarray = 500_000;
>
> double[maxarray] a, b, c, d;
>
> void main()
> {
> import std.stdio;
> import std.datetime;
>
> import std.random;
> for (int n = 0; n < maxarray; n++)
> {
> a[n] = uniform01;
> b[n] = uniform01;
> c[n] = uniform01 + 0.1;
> }
>
> void overhead() {}
>
> void foreach_loop()
> {
> foreach(n, elem; d[])
> elem = a[n] * b[n] / c[n];
> }
>
> void for_loop()
> {
> for (int n = 0; n < maxarray; n++)
> d[n] = a[n] * b[n] / c[n];
> }
>
> auto r = benchmark!(overhead,
> foreach_loop,
> for_loop)(10_000);
>
> import std.conv : to;
> foreach (i, d; r)
> writeln("Function ", i, " took: ", d.to!Duration);
> }
> /////////
>
>
> Depending on the machine this is run on, for() performs a
> factor 3-8 slower than foreach(). Can someone explain this to
> me? Or, taking for() as the norm, how can foreach() be so
> blazingly fast?
> Thanks!
The foreach loop behaves differently.
It does not modify d.
If you want it to modify the array you have to use a ref elem.
If you do you will see that foreach is a little slower.
More information about the Digitalmars-d-learn
mailing list