what is the advantage of string object as compared to string literal

后端 未结 6 2003
你的背包
你的背包 2021-01-02 16:59

i want to know where to use string object(in which scenario in my java code). ok i understood the diff btwn string literal and string object, but i want to know that since

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-02 17:28

    In most situations, you should use String literals to avoid creating unnecessary objects. This is actually Item 5: Avoid creating unnecessary objects of Effective Java:

    Item 5: Avoid creating unnecessary objects

    It is often appropriate to reuse a single object instead of creating a new functionally equivalent object each time it is needed. Reuse can be both faster and more stylish. An object can always be reused if it is immutable (Item 15). As an extreme example of what not to do, consider this statement:

    String s = new String("stringette"); // DON'T DO THIS!
    

    The statement creates a new String instance each time it is executed, and none of those object creations is necessary. The argument to the String constructor ("stringette") is itself a String instance, functionally identical to all of the objects created by the constructor. If this usage occurs in a loop or in a frequently invoked method, millions of String instances can be created needlessly. The improved version is simply the following:

    String s = "stringette";
    

    This version uses a single String instance, rather than creating a new one each time it is executed. Furthermore, it is guaranteed that the object will be reused by any other code running in the same virtual machine that happens to con- tain the same string literal [JLS, 3.10.5]

    There is however one situation where you want to use the new String(String) constructor: when you want to force a substring to copy to a new underlying character array like in:

    String tiny = new String(huge.substring(0, 10));
    

    This will allow the big underlying char[] from the original huge String to be recycled by the GC.

提交回复
热议问题