简体   繁体   English

提取功能会影响性能吗?

[英]Does extracting functions affect performance?

I'm considering dissecting long functions to several smaller ones and I'm concerned about performance. 我正在考虑将长函数分解为几个较小的函数,并且我担心性能。 Say we have a long function with many lines of code: 假设我们有一个包含很多代码行的长函数:

void f(){
....
}

Now if we extract pieces of work to separate functions: 现在,如果我们提取一些工作来分离功能:

void f(){
  f1();
  f2();
  f3();
} 

Does it usually affect performance? 它通常会影响性能吗? I'm in search of a general strategy to balance performance and good software design. 我正在寻找一种平衡性能和良好软件设计的总体 策略 Is it always a good practice to have small functions? 具有小功能总是一种好的做法吗? assume a class with a private member variable int something . 假设一个类的私有成员变量int something Is it free to return it by calling get_something() instead of making something public? 它是免费的,通过调用返回它get_something()而不是使something公开?

Assume functions as non-virtual and optimization level on /O3 . 假定在/O3上充当非虚拟和优化级别的功能。 The importance of the question is that if the first version is faster we will face a trade-off between maintainability and performance. 问题的重要性在于,如果第一个版本更快,我们将面临可维护性和性能之间的权衡。

If your functions are simple the compiler will usually inline them for you, thus there will be no overhead. 如果您的函数很简单,则编译器通常会为您内联它们,因此不会有开销。

Even if the compiler does not inline your functions, they would have to be part of a very hot path if the overhead of a function call was to matter. 即使编译器没有内联您的函数,如果函数调用的开销很重要 ,它们也必须成为非常热的路径的一部分。

Strive to write readable code first and worry about performance second. 力争先编写可读代码,然后再担心性能。 And only optimize for performance after you have profiled your application (with optimizations enabled) and demonstrated that the code in question is an actual performance bottleneck. 并且只有在对应用程序进行概要分析(启用优化)并证明所涉及的代码是实际的性能瓶颈之后,才能对性能进行优化。

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

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