What are the benefits of using identical String literals instead of a final variable?

前端 未结 6 1575
迷失自我
迷失自我 2020-12-08 19:25

I\'ve come across a class that includes multiple uses of a string literal, \"foo\".

What I\'d like to know, is what are the benefits and impact (in terms of object c

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 20:21

    They will be exactly the same. The literal is interned (any compile time constant expression that results in that string shares the same instance as all other constants/literals) in both cases and a smart compiler+runtime should have no trouble reducing both to the most optimized example.

    The advantage comes more in maintainability. If you want to change the literal, you would need only change one occurrence with a constant but you would need to search and change every instance if they were included inline.

提交回复
热议问题