0

I Have a class called car, this class have multiple methods (about 30) to handle things such: starting car, stopping, opening doors ...

  • The problem is that my program have thousands of instances of the class car. I noticed I can refactor the class into having member variables that define each instance of a car class, and for the methods they can be made into static methods that takes the instance of the car class as parameter and do the necessary things on it.
  • My question is: is static methods going to be better on memory usage or the refactoring doesn't worth it? in other words is using non-static methods going to take up memory for each instance of the car class?
  • The code for the methods is stored once in memory (not per instance). So in this respect there isn't a difference between static and non-static. For non-static you will need an instance that will occupy memory, but you intend to have such an instance anyway (to pass to the static methods). So bottom line - I don't see much difference memory-wise. – wohlstad Aug 27 '22 at 13:29
  • *thousands of instances of the class car* That is not a number that makes your app memory bound. Only optimize for memory when your measurements prove you're using too much of it. And then still the memory hotness will be caused by objects you didn't think off in the first place. Read https://ericlippert.com/2012/12/17/performance-rant/ – rene Aug 27 '22 at 13:54
  • Thank you guys for your comments, I really appreciate it! – Mohammed Sitni Aug 27 '22 at 14:54
  • 1
    Does this answer your question? [Performance of static methods vs instance methods](https://stackoverflow.com/questions/12279438/performance-of-static-methods-vs-instance-methods) – Charlieface Aug 27 '22 at 22:24
  • Note though: The performance difference is going to be so small that you will not notice it unless instantiating **many millions** of objects. In release (optimized) builds an unused `this` parameter will be optimized out. In your case there will be no difference at all, as you anyway need to pass the parameter. Just use the option that fits best with the semantics, most likely an instance method. – Charlieface Aug 27 '22 at 22:26
  • Thank you so much, this really helped me figuring out what best fits my project. – Mohammed Sitni Aug 28 '22 at 00:05

0 Answers0