Java: Is the method Integer.toString() better than adding empty string to integer type value? [duplicate]
Possible Duplicate:
Is conversion to String using (“” + <int value>) bad practice?
I am testing some Java codes with PMD rules. One of the rules for efficiency is a 'AddingEmptyString'. Below is a description for the rule.
Finds empty string literals which are being added. This is an inefficient way to con开发者_开发知识库vert any type to a String.
String s = "" + 123; // bad
String t = Integer.toString(456); // ok
Could you explain why Integer.toString is better than adding empty string to integer type value?
It's bad because the first way does more operations than the second. The compiler will translate the first line into the equivalent of
String s = "" + Integer.toString(123);
Which has an extra string concatenation when compared to
String t = Integer.toString(456);
Even if the compiler optimizes away the concatenation with the empty string, the purpose of the line of code is much more clear when Integer.toString is used explicitly.
in the first example you're instantiating a String object ("") and then another String object to hold the result of Integer to String conversion, 2 objects created in all;
The second you're only creating one string object, which is created when you do the Integer.toString()
It's also bad because String concatenation is a relatively expensive operation. Using StringBuilder would likely be slightly more efficient than your first fragment. You might note that you will commonly see something like System.out.println(""+i) where i is an int but this concatenation is quite unnecessary, not to say wrong. This is the equivalent of ...println(""+Integer.valueOf(i).toString()) which looks a lot more messy but does the same thing. ...println(i) works just fine.
精彩评论