Home > Blockchain >  c : is it better to have a global variable or create a local variable?
c : is it better to have a global variable or create a local variable?

Time:07-15

for example i have a library function which needs to be used for validating signatures,and is only called when requested.

lets say i have a library class to verify signature sigverify.hpp

class SigVerify
{
bool verifySignature(std::string path);
}

sigverify.cpp

bool Sigverify::verifySignature(std::string path)
{
 //verfies signature
 return true;
}

now assume that i compiled sigverify as library and linked it to my main service code Service.hpp

#include "sigverify.hpp"
class SeviceClass
{
 public:
 void makeLibCall();
 //is it better to declare a variable here and use it in my cpp
   SigVerify m_sigVerify;
 }

Service.cpp

void ServiceClass::makeLibCall()
{
 // OR declare a local variable here like this
   Sigverify m_sigVerify;
   bool result = m_sigVerify.verifySignautre(path);
}

the library call is only made in one place in my entire code, so i think it is better to create a local variable when there is a need to make the call? which is better in terms of performance??please help me :)

CodePudding user response:

Consider a third option mentioned in comments:

void ServiceClass::makeLibCall()
{
   static Sigverify m_sigVerify;
   bool result = m_sigVerify.verifySignautre(path);
}

m_sigVerify will be initialized once, when the function is called for the first time.

However, to know what is more performant you need to measure. There is no way around that. If the class is really not more than what you posted, then creating an object and calling a function can be expected to be not be more expensive than just calling the function. To be sure: measure.

  •  Tags:  
  • c
  • Related