Performance penalty for repeatedly dereferencing a pointer?

Hello, I often find myself doing the following:

Let's assume "person" is a class that has a member "age", and personptr is a pointer to a person object.

1
2
3
4
5
6

doStuff(personptr->age);
doMoreStuff(personptr->age);
andSomethingElse(personptr->age);
andSomethingElse(personptr->age);


Is this bad for performance? Is the following better or doesn't it matter?
1
2
3
4
5
6
7
8

int person_age = personptr->age;

doStuff(person_age);
doMoreStuff(person_age);
andSomethingElse(person_age);
andSomethingElse(person_age);
Unless you disable optimizations, the compiler can most likely convert the first into the second for you (if that makes the code faster).

Don't ever worry about speed or optimizing unless you know something is a bottleneck when you profile your runtime.
Last edited on
Unless the functions are inline or have internal linkage (that is unless the compiler can see the definitions of these functions), or the compiler can determine that the person object involved is not programmatically visible to those functions,

1
2
3
4
doStuff(personptr->age);
doMoreStuff(personptr->age);
andSomethingElse(personptr->age);
andSomethingElse(personptr->age);


is not semantically equivalent to

1
2
3
4
5
6
int person_age = personptr->age;

doStuff(person_age);
doMoreStuff(person_age);
andSomethingElse(person_age);
andSomethingElse(person_age);


(Any of those functions could have modified the age member of the person object involved, and the compiler would have to take that into account.)

But, as LB points out,
Don't ever worry about speed or optimizing unless you know something is a bottleneck when you profile your runtime.


Or to paraphrase it, in general, leave low level optimizations to the compiler - it is very good, probably better than you are, at doing that. Concern yourself with high level design decisions like choice of data structures and algorithms - the compiler can't decide for you whether you should use a std::vector<> or a std::set<>
Topic archived. No new replies allowed.