Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I make my private class methods static?

Is there a best practice for making private methods in classes static? I have a class with a few methods. Some of these can easily be made static, since they simply process data.

Should I make them static or just leave them as is? Is this more of a style issue? Are there performance considerations?

Edit: Method can be made static, but should it?

like image 492
MedicineMan Avatar asked Sep 03 '09 18:09

MedicineMan


1 Answers

If the methods don't access any of the type's state then they should be static.

Static method calls provide a performance gain over instance methods and the presence of a static method tells future readers of your code that calling this method will create no side effects in the the state of the current instance of the type.

The performance gain of a static method comes from the fact that the compiler does not have to emit callvirt instructions to call a static method. The callvirt instruction is handy for instance calls in that it does a null check prior to calling the method. However, when you call a static methods there is no need to check for null so the compiler is free to emit the faster call instruction which doesn't check for null.

like image 109
Andrew Hare Avatar answered Nov 06 '22 12:11

Andrew Hare