3

Would there be a difference in performance or memory if I used static classes in an object that has many instances?

Let's say I have thousands of instances and each is responsible for doing many functions on its own without any external managers.

Would it make sense to

  1. keep the class lightweight and have another class with many static methods responsible for object's functions, and pass many arguments required to perform these functions, or

  2. have private methods within the object's class itself and don't pass any arguments but use objects private variables to complete all required functions?

Daniel
  • 1,064
  • 2
  • 13
  • 30
  • Could you, please, clarify whether the data which will be passed around is stored inside the instances` members or will it come outside of the instances? – qqqqqqq Feb 01 '20 at 19:41
  • Basically question boils down to "if I implement instance methods manually by passing reference to just instance data to static method would it be much faster if I let compiler/runtime do exactly the same by passing reference to this instance data via `this` to instance methods" - generally answer to such "can I outsmart compiler" is resounding "no", but you should *try and measure yourself* as maybe you have very special case... or indeed you are smarter than all compiler's devs. – Alexei Levenkov Feb 01 '20 at 19:50
  • Best advice is to implement, measure and evaluate. Write a small program that implements your ideas, measure the performance and memory usage of each scenario and evaluate the results. – Simply Ged Feb 02 '20 at 00:02

1 Answers1

0

I will prefer the option 1. Static methods on paper are considered better performance wise as compared to instance methods. In reality there is very little difference. You try yourself to measure this. Also design wise, if the functions are not directly related to the class, they should not be part of that class.
For many arguments, you can create and object and pass it to the static methods. This will also help in better code organization and maintenance.

You can refer to this thread as well for more details:Performance of static methods vs instance methods

Usman Afzal
  • 376
  • 3
  • 9