简体   繁体   English

递归静态成员函数Vs普通成员函数

[英]Recursive static member functions Vs ordinary member functions

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? 可能的原因是什么?

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. 从技术角度来看,这是真实的(或至少它* 可能是真实的),因为每一个非静态成员函数调用包括一个不可见的this参数。 For example, if the height function in your example were nonstatic, its effective signature would be int height(Tree* this, Node* n) . 例如,如果示例中的height函数是非静态的,则其有效签名将为int height(Tree* this, Node* n) So if you don't need this , you do waste some nonzero number of cycles passing it. 所以如果你不需要this ,你会浪费一些非零循环次数。

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. 所以编写代码然而它最有意义,并且只有在分析器显示(a)您遇到问题并且(b)优化产生影响时才会担心进行微优化。

*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. *我说可能是真的,因为我怀疑大多数编译器无论如何都会优化掉未使用的参数,但我不是100%肯定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM