0

I have two questions that have been turning around in my head for some time and I hope that some knowledgeable person can answer them for me :)

  1. Is using static methods good/bad for performance during code execution (time)?
  2. How about memory? Do they use more memory than their instance methods counterparts?
Michael Oryl
  • 20,856
  • 14
  • 77
  • 117
tupini07
  • 518
  • 5
  • 13
  • indeed it is. I searched but it seems that not very well :) .. however my second question still stands. Does it have any impact on memory consumption? – tupini07 Feb 13 '15 at 16:21
  • the amount of memory a method takes is same whether it is a static method or an instance method. Once a method is called, it will create a new stack frame, copy all the arguments to that frame and do what you ask it it do. So memory wise no difference, even if there is, it would be negligible – Arkantos Feb 13 '15 at 16:25
  • Like Mike said, one difference I can see is the implicit `this` variable as first argument to all instance methods which is not applicable for static methods – Arkantos Feb 13 '15 at 16:30
  • 1
    Don't worry about it. Write good, clean, well-designed & well encapsulated code & you'll be fine. – kittylyst Feb 14 '15 at 13:17

2 Answers2

7

Static methods can theoretically perform infinitesimally better than instance methods, because no this pointer needs to be passed to them. However, I would strongly advise against paying any attention at all to this entirely inconsequential factoid, and choose static or instance methods based on what you want to accomplish, not on whether they might be one or two clock cycles faster per invocation.

The only way in which static methods could be thought of as using less memory than instance methods is the one meager machine word of stack space that they save by not having to be passed the this pointer. Again, this is not worth paying any attention to, for any practical usage scenario.

So, considerable impact on performance? Not a chance of it.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
0
  1. Yes and no.

The reason why it can be faster is simply that the actual method call can be resolved in compilation time. A non-static method invocation requires to resolve dynamically what is the actual implementation of that method given the object's class.

This overhead would become negligible for more CPU intensive methods. Also the VM might be able to optimize the non-static call...

So I would say that ultimately you need to run some benchmarks in order to figure out if there is any advantage for your case... I suspect that the gain would not be significant in most cases.

  1. There is no reference to an object (this) in the stack so there is some saving yet again I think this is quite negligible.
Valentin Ruano
  • 2,726
  • 19
  • 29