Looking up global variables instead of constructing them inside a c++ function -


question:

i have functions being called lot. inside each function, local variables constructed. these variables eigen::matrixxds sort of small (usually under 10 x 10). every call constructs same variable, on , on again, discards it.

i started thinking faster define these variables outside of function, , them up.

  1. why "looking up" of global variable faster re-constructing on , on again?
  2. should put global constants in namespace? go wrong approach?

first code:

i started off these 3 files.

first: functions.h

#ifndef functions_h #define functions_h  #include <eigen/dense>  eigen::matrixxd getmatrix();  #endif //functions_h 

second: functions.cpp

#include "functions.h"  eigen::matrixxd getmatrix() {     eigen::matrixxd mymatrix(4,4);     for(int = 0; < 4; ++i)     {         mymatrix(i,i) = 3.0;     }     return mymatrix; } 

third, main.cpp

#include "functions.h"  int main() {      for(int = 0; < 500000; ++i)         getmatrix();      return 0; } 

second code:

first, functions2.h:

#ifndef functions2_h #define functions2_h  #include <eigen/dense>  extern const eigen::matrixxd mymatrix;  eigen::matrixxd getmatrix2();  #endif //functions2_h 

then functions2.cpp

#include "functions2.h"  const eigen::matrixxd mymatrix = eigen::matrixxd::identity(2,2);  eigen::matrixxd getmatrix2() {     return mymatrix; } 

then different main.cpp

#include "functions2.h"  int main() {      for(int = 0; < 500000; ++i)         getmatrix2();      return 0; } 

if get functions returning same matrix, can generate once first time needed, without using global variable, using static local one.

eigen::matrixxd getmatrix() {    static eigen::matrixxd mymatrix{[](){         eigen::matrixxd m(4,4);         for(int = 0; < 4; ++i)         {             m(i,i) = 3.0;         }         return m;     }};     return mymatrix; } 

this uses lambda function initialize matrix, rather function. create copy of matrix every time, original matrix hidden users , cannot changed. copy elision cannot happen here, since source not non-static local variable. rvo can still done.

another option here return reference matrix, changing function to

const &eigen::matrixxd getmatrix() 

this avoid copy , still hides original matrix changes unless caller applies const_cast returned value.

for getmatrix2, can move global variable have getmatrix2 static.


Comments