-2

Which is the fastest code among the following ones?

void foo1 (int & a)
{
   a = 10;
}

or

void foo2 (void)
{
   GLOBAL_VARIABLE.a = 10;
}

(where GLOBAL_VARIABLE is a global class element with field 'a') ?

Is there any difference in variable access/write times between local and global variables?

user1403546
  • 1,680
  • 4
  • 22
  • 43
  • 1
    Run it and find out. – NathanOliver Jan 07 '16 at 14:31
  • 2
    You don't have any _local variables_, but a reference parameter. Why would you expect a difference? Where does `a` actually come from in your 1st version? – πάντα ῥεῖ Jan 07 '16 at 14:31
  • 1
    You do not have a local variable, but if you would, optimizing compiler can improve performance on local variables in some cases (by putting them into the register, for example). But I do not imagine you need to think about it yet. – SergeyA Jan 07 '16 at 14:32
  • 2
    @NathanOliver, cruel advice. I would be hard put to run a test which would measure this difference. – SergeyA Jan 07 '16 at 14:33
  • In that case you can't care. If you do care, you must have a larger system in which case you can try. – Martin Bonner supports Monica Jan 07 '16 at 14:43
  • @NathanOliver Thank you for your amazing suggestion but it's not only a matter of a single run/test (which - as far as I know, i.e. nothing - might depend also on the used compiler): I'd like to know from a theoretical point of view which is the fastest situation (something like accessing a vector is faster than an array) – user1403546 Jan 07 '16 at 14:50
  • @user1403546 _theoretical point of view_ is the worst starting point for optimization. Just throw that into your bin. – πάντα ῥεῖ Jan 07 '16 at 15:10

1 Answers1

0

It will depend. (On your program, on your hardware, on your compiler).

If it really matters, measure it and choose the fastest. If it doesn't matter, choose the clearest and least likely to introduce errors.

(As others have noted, you don't actually have a local variable - you have a parameter passed by reference.)