简体   繁体   中英

faster way to create object lombok builder vs manually declaration

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?

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.

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.

  1. Fluent Builder pattern

    • Better for readability
    • Optional attributes
    • Construction in multiple step

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.

  1. 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.

  2. Primary constructor . You prefer this way when all fields are required .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM