array traversal

BCS ao at pathlink.com
Tue Mar 20 15:09:22 PDT 2007


Reply to Tyler,

> arun wrote:
> 
>> i want to know during array traversal ,whether pointers do a better
>> job than indices by considering the code snippet
>> 
>> int [10]array;
>> foreach( value;array) {
>> //something
>> }
>> i heard that implementations decides which one to use.i want to know
>> how those two traversal differs?
>> 
> At least on x86/x64 they shouldn't differ.  They should both compile
> down to the pseudo-code x86 instruction
> 
> mov value,[array.ptr+sizeof(int)*index]
> 
> which is read as "move the value at the address
> (array.ptr+size(int)*index) into value" using flat pointer arithmetic
> (i.e. not C-style; use 1-byte increments always, even for types where
> sizeof(type) > 1 byte).  The above examples uses a bit of pseudo-code.
> The real version uses a few more instructions to make sure that index
> is within array's bounds (in debug mode) and temporarily store
> array.ptr and index in a CPU registers.
> 


I think that options he is taking about are these
for(T* ptr = &start; ptr !is &stop; ptr++)
{
  T value = *ptr
}

vs.

for(int i = 0; i< length; i++)
{
   T value = ptr[i];
}

only the second ever uses a multiplication





More information about the Digitalmars-d mailing list