RFR(S): 8067471: Use private static final char[0] for empty Strings
Remi Forax
forax at univ-mlv.fr
Wed Dec 17 18:49:20 UTC 2014
On 12/17/2014 11:22 AM, Lev Priima wrote:
> Hi,
>
> Please review space optimization in no args String constructor.
> Originally, it was already rejected once by suggestion in
> http://mail.openjdk.java.net/pipermail/core-libs-dev/2012-May/010300.html
> w/o formal justification of pros and contras. And enhancement was
> requested again by Nathan Reynolds.
>
> Issue: https://bugs.openjdk.java.net/browse/JDK-8067471
> Patch: http://cr.openjdk.java.net/~lpriima/8067471/webrev.00/
>
Hi Lev,
new String() is usually used by beginners that forget or doesn't know
that you they can use "" instead.
There is only one legit usage when you want a NullObject for a String
*and* you don't want to have a shared reference (something visible by
everybody).
You find 4 occurences of new String() in the JDK,
> jdk.httpserver/share/classes/sun/net/httpserver/Request.java:200: v =
new String();
> java.base/share/classes/sun/net/www/MessageHeader.java:508: v = new
String();
>
java.base/share/classes/java/lang/invoke/MethodHandles.java:829:MethodType
MT_newString = methodType(void.class); //()V for new String()
>
jdk.runtime/share/classes/sun/security/tools/policytool/PolicyTool.java:947:
String stringEntry = new String();
For the first two, the code is very similar and "" can be used instead
of new String().
The third occurence is just a comment.
The last occurence is typically a code written by a beginner, the code
use String.concat, do a kind of defensive copy on String (line 967).
Again, "" can be used instead of new String().
so my suggestion is to wait to have more information from Nathan
Reynolds before trying to fix something,
new String() is not the only way to have a String with an empty char array.
cheers,
Rémi
More information about the core-libs-dev
mailing list