c++ - Member Variable vs. Function Argument -


i´ve tried figure out if faster give function argument or use member variables. have following code.

class variable {     private:      public:         variable() {}         ~variable() {}          struct         {             static const int test = 3;         }testvar; };  class variabletransmit {     private:         variable var;      public:         variabletransmit() {}         ~variabletransmit() {}          void testfunc1(int test)         {             int foo = 2;             foo = test;         }          void testfunc2()         {             int foo = 2;                 foo = var.testvar.test;         }  };  struct {     static const int test = 3; }extvar;  int main(void) {     variabletransmit transmit;      clock_t prgstart, prgend;     prgstart = clock();      for(int = 0; <= 10000000; i++)     {         transmit.testfunc1(extvar.test);     }      prgend = clock();     printf("delivered: %.5f seconds\n\n", (float)(prgend - prgstart) / clocks_per_sec);      prgstart = clock();      for(int = 0; <= 10000000; i++)     {         transmit.testfunc2();     }      prgend = clock();     printf("member: %.5f seconds\n\n", (float)(prgend - prgstart) / clocks_per_sec);      return 0; } 

i tested code , surprise testfunc1 , testfunc2 have identical processing speed. had thought testfunc1 faster 1 since gets value argument out of struct , has set it, while testfunc2 has access var object , value out of struct inside object. compiler specific optimizing (i'm using vs2010 btw.) or did overlook something?

edit: removed second question being opinion based.

your example highly optimized visual-c++ compiler. testfunc1 might slower, depending on register used pass test, while testfunc2 copies always same virtual adress.

why that? variable var created on stack. created upon object creation, , compiler can predict virtual address. (you create variable object on heap , have longer execution time.)

[about public/private-things: usually, can please. - - believe, in multithreaded environments, making internal structures of classes public poses higher risk of accidental race conditions.]


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -