foreach range with index

9il via Digitalmars-d digitalmars-d at puremagic.com
Tue Jun 13 20:53:07 PDT 2017


On Wednesday, 14 June 2017 at 03:06:26 UTC, Luís Marques wrote:
> On Wednesday, 14 June 2017 at 02:54:30 UTC, 9il wrote:
>> Random access iteration is more expensive then front/popFront 
>> in general case.
>> For arrays it is not true. But for many other kinds of ranges 
>> it is. For example ranges that do not have contiguous memory 
>> representation (strided vectors, flattened matrixes and etc)
>
> I'm not sure I understand what you are saying. I was suggesting 
> that foreach(range) would iterate range[0...length] in that 
> order. Wouldn't that be an equivalent access pattern to 
> front/popFront?

-------A
foreach(__i; 0 .. r.length)
{
     auto e = r[__i];
}


-------B
for (auto __r = range; !__r.empty; __r.popFront())
{
     auto e = __r.front;
     ...
}

They are equivalent, but "A" is slower then "B" in general case.
So, B is preferred.



More information about the Digitalmars-d mailing list