Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance cost of Method Encapsulation

Tags:

c#

Is there a performance cost to encapsulating methods? A very brief, arbitrary example:

        public static decimal Floor(decimal value)
        {
            return Math.Floor(value);
        }

Would the above function be inlined? And if so, would it be the exact same as calling Math.Floor() from the code? I did Google before writing this.

like image 516
Krythic Avatar asked Sep 19 '15 01:09

Krythic


1 Answers

Method likely will be inlined (at JIT time, C# compiler does not inline method in IL). Even if not cost is unlikely to impact your overall program. Since optimization and performance numbers are specific to particular code/application you need to measure your case if you see performance problem.

In particular Writing Faster Managed Code: Know What Things Cost article on MSDN gives following estimate for cost of method call: max 6.8 nano-seconds (for 2003 level machine) if the call is not optimized.

Consider reading the rest of the article. In particular Table 3 talks about not only the cost of method calls, but also how much do the operations as trivial as addition, subtraction, multiplication and division cost.

If you need to confirm whether method is inlined - it is covered in many SO questions like Can I check if the C# compiler inlined a method call?

like image 200
displayName Avatar answered Nov 13 '22 00:11

displayName