views:

19

answers:

1

Suppose you have a private static method called Inst() which allows the class to retrieve the single instance of itself in the application in its static methods. Maybe Inst() is defined something like..

return App::GetApp()->CurrentState()->MyClass(); // Inst returns a reference

Compare this...

// I prefer this
Inst().DoThis();
Inst().DoThat();
Inst().DoFoo();

to...

MyClass inst = Inst();
inst.DoThis();
inst.DoThat();
inst.DoFoo();

In an application where performance is fairly important, is the overhead in the first set of functions non-trivial? Are modern compilers able to optimize these things out?

I realize profiling would answer my question in my case, but I'm looking for a rule of thumb here. How beneficial is it to store existing data in an local variable rather than re-retrieving it, or is this re-retrieval commonly optimized by modern compilers?

A: 

You worry about the wrong things and have answered the question yourself. Profile it and optimize if it's a bottleneck.

Anyway: Inst() is probably going to be inlined, so there is no function call overhead and as it is static and the result is not depending on any obvious outside parameters it could be possible for compilers to optimize it away entirely.

pmr