Java String Memory Optimization: Understanding "String s = new String("silly")"
Concern has been raised regarding the recommendation to avoid writing Java code like "String s = new String("silly")". While this advice is valid for optimizing memory usage in the case of String objects, it may not be applicable to other classes.
Why is "CaseInsensitiveString cis = new CaseInsensitiveString("Polish")" acceptable?
The object "cis" is an instance of the CaseInsensitiveString class. Unlike String, CaseInsensitiveString is a user-defined class that requires a constructor to create an object. Therefore, the syntax "CaseInsensitiveString cis = new CaseInsensitiveString("Polish")" is necessary to initialize the object with the specified string value.
How to make CaseInsensitiveString behave like String for literal initialization?
To enable literal initialization for CaseInsensitiveString as it is for String, one could implement the following:
Why is it okay to directly pass a literal to String?
String is a special class in Java. It has a predefined pool of interned strings, where duplicate string literals are stored as references to the same object. This eliminates the need for multiple String objects for the same string value, reducing memory consumption.
The above is the detailed content of Why is 'CaseInsensitiveString cis = new CaseInsensitiveString('Polish')' acceptable while 'String s = new String('silly')' is discouraged for memory optimizatio. For more information, please follow other related articles on the PHP Chinese website!