2

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 convert 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?

Community
  • 1
  • 1
  • See also http://stackoverflow.com/questions/1572708/is-conversion-to-string-using-int-value-bad-practice and http://stackoverflow.com/questions/2506474/is-concatenating-with-an-empty-string-to-do-a-string-conversion-really-that-bad – polygenelubricants Oct 20 '10 at 02:16
  • 1
    I use the former well, always, over the latter. Premature optimization is the r... anyway. Who says `"" + 123` is bad? :p Unless there is a *specific* "too slow" performance case tested (and verified), I'd argue *for* the former. –  Oct 20 '10 at 02:16
  • 1
    I also use the former. However correct, the latter is a good example if Java's gawkiness. – Tony Ennis Oct 20 '10 at 02:24
  • Given that StringBuilder.append(int) eventually calls Integer.toString(int) what do you think ? – mP. Oct 20 '10 at 03:54

3 Answers3

6

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.

Geoff Reedy
  • 34,891
  • 3
  • 56
  • 79
  • 2
    Actually "" + 123 ends up being a new StringBuilder().append("").append(123).toString(). – mP. Oct 20 '10 at 03:53
-1

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()

Anatoly G
  • 4,112
  • 2
  • 21
  • 23
-1

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.

Phasmid
  • 923
  • 7
  • 19