Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cost of passing variables to functions

Tags:

c++

c

I am unsure about how function calls are translated and I am afraid that passed variables are copied into local variables when they don't need to be. I could avoid unnecessary copying by using global variables, but that cannot be a good solution...

1) When variables are not changed in the target function, would it be better to pass them as pointers, references, or const?

void fkt1(int i, int j){
  do_something();
  printf("%d", i+j);
}

int main(){
  int i = 5;
  int j = 6;
  fkt1(i, j);
}

2) Is it expensive to pass variables to a function when they are not used within it. E.g., to keep a common interface, such as:

template <typename T>
void fkt2(T a, T b, int len = -1){ 
  do_something();
  printf("%d", a+b);
}

template<>
void fkt2<char*>(char* a, char* b, int len){
  do_something();
  strcpy(a+len, b);
  printf("%s", a);
}

or

class base{
public:
  virtual bool calc(int i, int j, int k, int l) = 0;
  base *next1;
  base *next2;
}

class derived1 : public base{
public:
  bool calc(int i, int j, int k, int l){
    return (next1->calc(int i, int j, int k, int l) || 
            next2->calc(int i, int j, int k, int l))
  }
}    

class derived2 : public base{
public:
  bool calc(int i, int j, int k, int l){
    return (return i+j > 5)
  }
}    

class derived3 : public base{
public:
  bool calc(int i, int j, int k, int l){
    return (return j*k < l)
  }
}    

Comments are much appreciated.

like image 442
st12 Avatar asked Nov 28 '22 04:11

st12


1 Answers

Don't worry about the performance issues at this point.

Focus on the algorithmic cost of your function, not the trivial things: guessing performance issues is a bad idea.

If you really encounter performance issues and have maintainable code, it will still be time to improve it.

Now to really answer the question:

You may pass const references when the object you have to pass really shouldn't be copied. If you have to pass integers, or simple structs (aka. small types), using a const reference or even a pointer is probably too much work: you will clutter the code with uneeded complexity were the compiler would probably have optimized things anyway.

like image 134
ereOn Avatar answered Dec 21 '22 20:12

ereOn