Local or global variables in frequently called functions?

D

danep2

Let me start by saying that this is more a question about principle
than practice - with the speed of today's computers it's probably
rarely an actual issue. Still I'd like to know...

If I have a function that is called thousands of times per second, it
seems to me that, performance-wise, it would be best to make all
variables used in it global, so that memory for them doesn't have to
be allocated and released with each call. However, I know this
clutters up the name space and can make the code more bug-prone.

Would it ever make sense to use global variables over local ones in
this situation? Would the same answer apply to threads instead of
functions? Thanks for satisfying my curiosity!
 
E

Erik Wikström

Let me start by saying that this is more a question about principle
than practice - with the speed of today's computers it's probably
rarely an actual issue. Still I'd like to know...

If I have a function that is called thousands of times per second, it
seems to me that, performance-wise, it would be best to make all
variables used in it global, so that memory for them doesn't have to
be allocated and released with each call. However, I know this
clutters up the name space and can make the code more bug-prone.

Would it ever make sense to use global variables over local ones in
this situation? Would the same answer apply to threads instead of
functions? Thanks for satisfying my curiosity!

Since local variables are allocated on the stack the cost of allocation
is virtually zero (it comes for free with the stack-frame creation). If,
however, the variables contains an object with non-trivial constructor
and/or destructor you would have to pay the price of running these on
each function call. If that is not acceptable you might use static
variables.

Using static variables is unfortunately not a very good idea if you use
threads since two threads running concurrently would be accessing the
same variables at the same time, to solve this you would have to use
either normal local variables, or thread-local variables (if your
platform supports it). Either way, global variables is not a good idea.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,263
Messages
2,571,064
Members
48,769
Latest member
Clifft

Latest Threads

Top