Performance benefits of a static empty array instance

前端 未结 4 1646
夕颜
夕颜 2020-12-11 17:47

It seems common practice to extract a constant empty array return value into a static constant. Like here:

public class NoopParser implements Parser {
    pr         


        
4条回答
  •  有刺的猬
    2020-12-11 18:28

    Is the VM not able to roll all empty String arrays into one?

    It can't do that, because distinct empty arrays need to compare unequal with ==. Only the programmer can make this optimization.

    Contrast this practice with returning an empty String: we're usually perfectly happy writing return "";.

    With strings, there is no requirement that distinct string literals produce distinct strings. In every case I know of, two instances of "" will produce the same string object, but maybe there's some weird case with classloaders where that won't happen.

提交回复
热议问题