Reputation: 132
Between these 3 way to create an object, which one is the faster in time of execution ?
Amount.builder().categoryCode("A").coveredAmount(new
BigDecimal(100)).build();
or
Amount cva1 = new Amount();
cva1.setCoveredAmount(new BigDecimal(100));
cva1.setCategoryCode("A");
or
Amount cva1 = new Amount(new Bigdecimal(100), "A");
And the number of fields can be made difference ?
Upvotes: 2
Views: 833
Reputation: 3324
Beyond the performance comparison (peanuts btw...) you should not use a object-creation strategy based on his execution time but merely on your real need , requirements and best practices.
Fluent Builder pattern
Remark
: don't use this pattern to hide the fact that your class defines too many fields... use pattern like extract class
instead of going through a builder construction.
Javabean style
. This type of construction is (IMO) a bad practice because the time between the no-arg construction and calls to setters to initialize it, the object stills in an inconsistent state.
Primary constructor
. You prefer this way when all fields are required
.
Upvotes: 2
Reputation: 418
Lets evaluate how many stack frames each syntax has (just a rough diagram, excuse my brevity):
1) builder() ->returns -> categoryCode() -> return this -> coveredAmount() -> return this
-> new BigDecimal() -> return BigDecimal -> return this -> finally build() -> returns Amount
So total 6 function calls.
2) ctr call -> return Amount -> setter -> bigdecimal -> return bigdecimal -> return setter -> (same again as last step)
So total 5 calls
For 3) only 2 function calls
By above analysis 3rd syntax wins but your compiler might optimize in such manner that all three would have similar execution time.
Upvotes: 2