(I see there are a lot of similar questions, but answers are not really what I am interested at.)
The thing that is bugging me is indirection. If I’m writing something, I do tend to inline as much stuff as possible. I might be less strict about it in compiled language hoping that compiler will do all the inlining for me. Still adding layers of indirection feels to me like “I’ll just add some more burden onto user in runtime so that I could have nicer code here” – something that could be solved with either a comment or a different design (which I would actually prefer but it would take some more time). Seeing a small function that is used only once I have to actually fight the urge to inline it. Having a multitude of single-use classes makes me want to create a different (and usually totally procedure-oriented) solution.
How bad is that? How many layers of indirection are actually OK to have?
2
There is no question that indirection (of the type you describe) is for the programmers benefit. What you may not be considering is this:
- Programmer time is very expensive, but
- Method calls are not.
Nicer code isn’t just a conceit; it has profound practical concerns. Every minute that you spend comprehending a piece of code that you didn’t refactor into a method (accompanied by its own small collection of unit tests to prove that it still works) is one less minute that you can spend making improvements to the software or adding new features.
9
There’s a good reason Knuth said premature optimization is the root of all evil:
- If your program isn’t correct, it doesn’t matter how fast it runs.
- Most performance gains come from optimizing a small amount of code (the 80-20 rule).
- The compiler is probably better at inlining and other such mechanical optimizations than you.
Write for correctness and clarity first. Measure. Decide if you actually have a performance problem. If you do, find the bottleneck. Then you may optimize.
3
Seeing a small function that is used only once I have to actually fight the urge to inline it.
That’s bad. It’s usually bad for readability and sometimes also bad for performance.
The following is rather Java specific, but may apply to other compilers working with statistics.
If you don’t inline a method, the compiler may chose to do it or not. If the method gets called rarely, it won’t get inlined and it doesn’t make the code larger. This leaves more room for inlining of more important methods and also loop unrolling.
If you inline it, it can’t be “out-lined” and can hinder the optimizations. This is no theory, see e.g. the comment at line 269 of this library class.