Question

Is it true that recursive functions are faster when the functions are declared as static member functions (instead of ordinary member functions). For example something like this:

class Tree {
  Node* p;
public:
  static int height(Node* n){
     .......
     int lh = height(n->left);
     int rh = height(n->right);
     ......
  }
};

What could be the possible reason for this?

Was it helpful?

Solution

In a technical sense this is true (or at least it may be true*) because every nonstatic member function call includes an invisible this parameter. For example, if the height function in your example were nonstatic, its effective signature would be int height(Tree* this, Node* n). So if you don't need this, you do waste some nonzero number of cycles passing it.

However, in practice it's very unlikely to matter (depending on exactly what you're doing, of course). So write the code however it makes the most sense, and only worry about making micro-optimizations if the profiler shows that (a) you have a problem and (b) the optimization makes a difference.

*I say may be true because I suspect most compilers will just optimize away the unused parameter anyway, but I'm not 100% certain of that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top