oops, small correction, in the second code sample it should read:

 if (xOrY)
  {
     offset = (char*)&(test.y) - (char*)&test;
  }
  else
  {
     offset = (char*)&(test.x) - (char*)&test;
  }


On Mon, May 30, 2011 at 3:02 PM, Oleg Krupnov <oleg.krup...@gmail.com> wrote:
> This question is related to C language, rather than Obj-C.
>
> I have a data structure
>
> typedef struct
> {
>   int x;
>   int y;
> } A;
>
> In my code, I have a function foo(bool xOrY) that runs a long-lasting
> loop that iterates through a huge array of A structures and for each
> structure, it should get x or y field. The choice of x or y is the
> same on each iteration, but may change between different calls of
> foo(bool xOrY).
>
> void foo(bool xOrY)
> {
>   for(int i = 0; i < count; ++i)
>   {
>      if (xOrY)
>      {
>          int value = a[i].y;
>          ...
>      }
>      else
>      {
>          int value = a[i].x;
>          ...
>      }
>   }
> }
>
> I am looking to optimize this code, because the line if(xOrY) yields
> the same result on each step. So I am thinking about this code:
>
>
> void foo(bool xOrY)
> {
>   struct A test;
>   size_t offset = 0;
>   if (xOrY)
>   {
>      offset = (char*)&(a.y) - (char*)&a;
>   }
>   else
>   {
>      offset = (char*)&(a.x) - (char*)&a;
>   }
>
>   for(int i = 0; i < count; ++i)
>   {
>          int value = *(int*)((char*)a + offset);
>   }
> }
>
>
> Is this approach valid at all? The compiler doesn't show any problem,
> but I wonder if there can be any caveats related to structure aligning
> etc.? It seems like it should not be a problem, because I am measuring
> the offset in run time, but I am not quite sure...
>
> I also thought about using a function pointer to switch between two
> tiny functions, one of them returning x and the other y from a given
> struct instance, but it seems somewhat more expensive than the above
> approach (push/pop param from stack, call, return)
>
> Thanks a lot!
>
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to