Why does EnumSet have many overloaded “of” methods?

后端 未结 4 2066
[愿得一人]
[愿得一人] 2021-01-01 10:55

While going through the EnumSet of method, I have seen multiple overloaded implementations of of method:

publ         


        
4条回答
  •  感情败类
    2021-01-01 11:18

    Because that class was designed by Josh Bloch, and that guy knows how things work. :) Besides creating an array, the varargs method contains the loop, which is more work for the JIT to optimize the code.

    For example, if we look at the implementation of the overloaded version with five parameters:

    result.add(e1);
    result.add(e2);
    result.add(e3);
    result.add(e4);
    result.add(e5);
    

    we notice that it is some kind of an already unrolled loop that could look like:

    for (E e : Arrays.asList(e1, e2, e3, e4, e5)) {
       result.add(e);
    }
    

    Also, shorter and simpler methods are more likely to be inlined than longer and more complex ones.

提交回复
热议问题