简体   繁体   中英

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 . Is it free to return it by calling get_something() instead of making something public?

Assume functions as non-virtual and optimization level on /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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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