Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the compiler discard empty methods?

Would C# compiler optimize empty void methods away? Something like

private void DoNothing()
{
}

As essentially, no code is run aside from adding DoNothing to the call stack and removing it again, wouldn't it be better to optimize this call away?

like image 354
MechMK1 Avatar asked Feb 11 '15 08:02

MechMK1


1 Answers

Would C# compiler optimize empty void methods away?

No. They could still be accessed via reflection, so it's important that the method itself stays.

Any call sites are likely to include the call as well - but the JIT may optimize them away. It's in a much better position to do so. It's basically a special case of inlining, where the inlined code is empty.

Note that if you call it on another object:

foo.DoNothing();

that's not a no-op, because it will check that foo is non-null.

like image 60
Jon Skeet Avatar answered Oct 22 '22 02:10

Jon Skeet