tags:

views:

128

answers:

5

What is the relative performance cost of calling a method over in-line code?

+2  A: 

Same as in C++. Basically a call and a return, plus setting up parameters. Note, though, that the JIT can inline method calls - so it may not be as expensive in a particular context as you think.

TomTom
+14  A: 

That will depend on many things

  • Whether the JIT inlines it for you
  • Whether it's virtual
  • The number and size of parameters
  • Whether it's an instance method (with the implicit nullity check)
  • Whether there's a return value (and its size if so)

It's very, very unlikely to be your bottleneck though. As always, write the most readable code you can first, and then benchmark it to see whether it performs well enough. If it doesn't, use a profiler to find the hotspots which may be worth micro-optimising.

Jon Skeet
in case of c# 2nd point is questionable. CSC emits `callvirt` for every method call
Andrey
@Andrey: Using `callvirt` on non-virtual methods doesn't prevent the JIT to inline that method.
Steven
@Steven i didn't say it prevents inlining. I just told that virtual or not doesn't affect emitted instruction
Andrey
@Andrey: Just because it's callvirt doesn't mean the JIT will actually resolve it virtually. If it spots that it's not a truly virtual method it won't need to use a vtable lookup.
Jon Skeet
+1  A: 

Insignificant. Every call in .net, at least for C# is virtual call even if method is not marked virtual, consider it.

Andrey
This doesn't mean that such is a virtual call. `callvirt` ensures the JIT adds a null check before calling any instance method. Still the JIT can choose to inline these methods when it sees they are not virtual.
Steven
+1  A: 

The performance cost is so inconsequential as to be irrelevant in comparison to making the code easy to read and its intent clear.

Thomas
You can generally optimize for a subset of {speed, memory, reliability, programmer efficiency}. I've found that if you optimize for programmer efficiency first, the others are fairly easy to do after. Any other ordering doesn't work as well.
clintp
Couldn't agree more. If the intent of the code is easy to grasp by other programmer's, then performance efficiencies can be found later at a lower resource cost.
Thomas
+3  A: 

There is a cost associated with method calls;

Arguments need to be pushed on the stack or stored in registers, the method prolog and epilog need to be executed and so on. The cost of these calls can be avoided by In-lining.

But, JIT uses a number of heuristics to decide whether a method should be in-lined. Following factors influence JIT, not to In-line a method.

  • Methods that are greater than 32 bytes of IL
  • Virtual functions
  • Methods that have complex flow control
  • Methods that contain exception-handling blocks
  • If any of the method's formal arguments are structs

Reference: Method Inlining

Asad Butt