Reputation: 17557
Does any one know what is the performance impact when using many parameters in constructor (10+) compared to setters?
I my case the model object is not valid without any of those parameters, so I am using single constructor.
I know that there is not significant difference either way, but I am asking if anyone knows whats actually going on in both cases.
I am asking for performance because the application is Android application that can be run on older devices without JIT.
Also it would be nice if we know the optimal solution.
Upvotes: 1
Views: 1414
Reputation: 10900
In most cases, if you have such a situation, it's a clear indication that your code needs (some) refactoring. None of the 2 solutions are good (i.e. big parameter list in constructor vs. setters). Also, given the fact that you can't force the clients of that object to call the setters, some runtime errors can easily occur because of this.
As for the performance part: no, performance impacts don't happen because of this. There is no reason why it should.
Upvotes: 0
Reputation: 726489
The performance implication of using the setters vs. the constructor is negligible, because roughly the same thing is going on in both instances: data passed to a method gets stored in an instance variable.
With ten setters you pay the price for nine additional method calls, but they are so extremely cheap that you are not likely to find any difference, especially if they get inlined by JIT compiler.
Logical implications are a lot more severe: if your object is not valid until you set all ten instance variables, then you definitely need to use a constructor with ten parameters: performance gains, real or not, are secondary to the logical integrity of your class, which should not be compromised.
Upvotes: 3
Reputation: 2874
You can encapsulate all the parameters in a single object, and pass it as a parameter to your constructor.
Upvotes: -1