Generally, I read that large methods benefit from some sort of inlining and the C# compiler does this sort of micro-optimizations automatically. I understand that if a method is called just one time in an enclosing method, performance might improve when inlined even if the method itself is large. However, if a large method is called in many places, performance could decrease if it is inlined, because it reduces the locality of reference. I know that all method calls have a cost such as adding to evaluation stack etc., So, my question is how do we find reduction in instruction count when inlined and the performance impact to determine if a method can benefit from inlining manually? The idea is to inline method calls selectively and manually for performance improvements. Any ideas and thoughts on this subject will be appreciated.
As this question is asked on
softwareengineering.stackexchange.com, where code quality is a major concern, my short answer is: don't waste your time with the question what the performance impact is of manually inlining methods unless you plan to create your own compiler/runtime system.
Let the compiler and runtime system decide about inlining and similar micro-optimizations. As a software engineer, you should aim at readable code with highest priority. Optimization generally makes code less readable (like manually inlining code, creating huge monster methods), and most of the time has a performance impact that you won't notice.
- Write the most readable code possible.
- Check whether you have any performance problem.
- If not, you're fine.
- If you have performance problems, use a profiler to find the real bottleneck (most probably, it won't be anything around inline-able methods).
- Optimize the bottleneck, and only the bottleneck.
- Verify that the optimization really improved something. Otherwise roll back to the original, more readable code.
- If necessary, repeat that cycle.