new String() vs literal string performance

前端 未结 4 2088
名媛妹妹
名媛妹妹 2020-12-05 15:07

This question has been asked many times on StackOverflow but none of them were based on performance.

In Effective Java book it\'s given tha

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 15:18

    as already have been answered the second retrieves the instance from the String pool (remember Strings are immutable).

    Additionally you should check the intern() method which enables you to put new String() into a pool in case you do not know the constant value of the string in runtime: e.g:

    String s = stringVar.intern();
    

    or

    new String(stringVar).intern();
    

    I will add additional fact, you should know that additionally to the String object more info exist in the pool (the hashcode): this enables fast hashMap search by String in the relevant data Strtuctures (instead of recreating the hashcode each time)

提交回复
热议问题