faster way to create object lombok builder vs manually declaration

☆樱花仙子☆ 提交于 2020-05-15 08:04:29

问题


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 ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/61410500/faster-way-to-create-object-lombok-builder-vs-manually-declaration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!