Re: Member variable versus local variable access performance
Francis Glassborow wrote:
On Oct 24, 3:31 pm, btm...@gmail.com wrote:
Would it be more efficient to keep member variables as part of the
class in which to insert the data? Or just declare local variables
inside the method each time its called?
Another option is to use a static local variable. Being static means
that it will only be constructed on the first entry to the function.
Being local means that it will not clutter up external code. And
finally, the object will be destroyed when the program ends.
True, but an extra level of run-time indirection will be necessary to
avoid multiple constructions, and contention will become an issue if the
function is used by multiple threads. Given:
extern "C" int init();
extern "C" int f_auto() { int i = init(); return i; }
extern "C" int f_static() { static int i; return i = init(); }
GCC implements f_auto:
_f_auto:
LFB2: pushl %ebp
LCFI0: movl %esp, %ebp
LCFI1: subl $8, %esp
LCFI2: call L_init$stub
leave
ret
For f_static, OTOH:
_f_static:
LFB3: pushl %ebp
LCFI3: movl %esp, %ebp
LCFI4: pushl %ebx
LCFI5: subl $4, %esp
LCFI6: call L5
"L00000000001$pb":
L5:
popl %ebx
call L_init$stub
movl %eax, __ZZ8f_staticE1i-"L00000000001$pb"(%ebx)
addl $4, %esp
popl %ebx
leave
ret
An exra, "private" call has been imposed to enforce the function-scope
static semantics, even for this trivial case. The code is larger, the
static variable's storage is always reserved (whether needed or not),
and the single instance must be shared by all threads that need access
to it. Function-scoped static variables can be very useful, but I would
not advocate them as a general-purpose optimization.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]