Reputation: 150
I have a simple question. I have a class that does not have any variables, it is just a class that has a lot of void functions (that display things, etc.). When I create an object of that class, would it be better/more efficient to pass that one object through all my functions as the program progresses, or to just recreate it every time the program goes into a new function? Keeping in mind, that the object has no variables that need to be kept. Thanks in advance for any help.
Upvotes: 0
Views: 83
Reputation: 179
if the functions in the otherwise empty class never change... consider making them static. or put them in a namespace instead of a class.
on the other hand... if the functions are set once at runtime, like say you pick which display functions to use based on os, then store them in a global. or singleton.
on the gripping hand... if the functions are different for different parts of the greater code... then yes you'll have to somehow deliver it to whatever functions need it. whether you should create once and pass many times - or pass never and create as needed, really depends on the specifics of your application. sorry, there's no universal answer here.
Upvotes: 0
Reputation:
For performance concerns, there is almost no difference. Passing an object as argument will cost you a (very tiny) bit at runtime. Recreating object will not (assuming compiler optimizations).
However, if you ever have plans to introduce some state (fields), or have two implementations for those void
methods, you should pass an object, as it greatly reduces refactoring cost.
Summarize: if your class is something like Math
where methods stateless by nature, stick with @Amit answer and make it static. Otherwise, if your class is something like Canvas
or Windows
and you have thoughts on implementing it another way later, better pass it by reference so you can replace it with abstract interface and supply actual implementation.
Upvotes: 0
Reputation: 46323
It makes much more sense that the class only has static functions and no instance is necessary at all. You have no state anyway...
Upvotes: 4