opStar

0ffh frank at frankhirsch.youknow.what.todo.net
Tue Nov 13 13:32:53 PST 2007


Bruno Medeiros wrote:
 > How would the pointer idiom have any advantage in terms of performance??
 > (versus say, structs with hasNext() and next() member functions)

Let me take a guess, using arrays and foreach as an example instead of
general iterables and iteration.

Foreach with pointers:

   struct array(T)
   {
     T* first;
     T* after;
   }

   void foo(array!(Bar) baz)
   {
     // iterate over the members of baz, and doSomethingWith them
     // the sourcecode
     //   foreach (elem;baz)
     //     doSomethingWith(elem);
     // gets translated to something alike
     for (Bar* elemPtr=baz.first;elemPtr<baz.after;++elemPtr)
     {
       doSomethingWith(*elemPtr);
     }
   }

Using reset(), hasMore() and getNext()
(I know this is only one of several possibilities)

   struct array(T)
   {
     // internal data structure irrelevant
     T reset()
     {
       // set internal position to first element
     }
     bool hasMore()
     {
       // check that position is not beyond end
     }
     T getNext()
     {
       // return current element and increase position
     }
   }

   function foo(array!(Bar) baz)
   {
     // iterate over the members of baz, and doSomethingWith them
     // the sourcecode
     //   foreach (elem;baz)
     //     doSomethingWith(elem);
     // gets translated to something alike
     baz.reset();
     while (baz.hasMore())
     {
       Bar elem=baz.getNext();
       doSomethingWith(elem);
     }
   }


Now, where there used to be a few pointer accesses in the other
version, we have two function calls per iteration.
In the absolute best case (the array does internally work similar
to the example above, and functions are inlined) we may get the same
performance for both. In all other cases the second option is slower.

Regards, Frank








More information about the Digitalmars-d mailing list