coproc
coproc

Reputation: 6257

Most efficient way of accessing coordinates

Given the following definition

union {
  double coords[3];
  struct {
    double x,y,z;
  };
} p;

it is possible to access the coordinates of a 3D point both by index and by name (both ways have their advantages). But are they equivalent? More precisely: will the following expressions

... p.coords[0] ... p.x ...
... p.coords[1] ... p.y ...
... p.coords[2] ... p.z ...

(pairwise, for each line) generate the same (assembly) code? Is there a difference in efficiency between the two ways of accessing a coordinate?

Upvotes: 0

Views: 106

Answers (1)

Javid
Javid

Reputation: 2945

p.x,... might be faster, however there's not much difference one would notice. When you use array, there is a time spent on multiplication the size of each double in the given index to get the desired memory address; but in the other method (p.x,...) the compiler knows what address we are accessing so that calculation is not required. However, if the compiler is smart enough to figure out constant numbers, there would be no difference.

Upvotes: 2

Related Questions