Peter is a DZone MVB and is not an employee of DZone and has posted 161 posts at DZone. You can read more from them at their website. View Full User Profile

String.valueOf(int) vs "" + int

01.19.2012
| 7998 views |
  • submit to reddit
There are a number of reasons I  prefer either

 

int i = ...
String s = "" + i;
String s = String.valueOf(i);

These include

  • simplicity
  • clarity
  • efficiency
  • performance

Personally I prefer efficiency for the developer as the performance difference is very, very small. IMHO, "" + i is also simpler and clearer, but that is a matter of taste.

 

Comparing the performance difference

public static void main(String... args) throws IOException {
    for (int i = 0; i < 3; i++) {
        long svo = perfStringValueOf();
        long qqp = perfQuoteQuotePlus();
        System.out.printf("String.valueOf took an average of %.3f us and \"\"+ took an average of %.3f us%n", svo / 1e3, qqp / 1e3);
    }
}

private static long perfStringValueOf() {
    long start = System.nanoTime();
    final int runs = 100000;
    String s;
    for (int i = 0; i < runs; i++) {
        s = String.valueOf(i * i);
        // ensure s is not optimised away
        if (s.length() < 1) throw new AssertionError();
    }
    long time = System.nanoTime() - start;
    return time / runs;
}

private static long perfQuoteQuotePlus() {
    long start = System.nanoTime();
    final int runs = 100000;
    String s;
    for (int i = 0; i < runs; i++) {
        s = "" + i * i;
        // ensure s is not optimised away
        if (s.length() < 1) throw new AssertionError();
    }
    long time = System.nanoTime() - start;
    return time / runs;
}

prints

 

String.valueOf took an average of 0.140 us and ""+ took an average of 0.243 us
String.valueOf took an average of 0.063 us and ""+ took an average of 0.058 us
String.valueOf took an average of 0.044 us and ""+ took an average of 0.058 us
This suggest that using String.valueOf will save 0.014 micro-seconds. However, using "" + will save you, the developer far, far more than that in time. (possibly a million times over)

As I have mentioned in previous article, if performance is really critical, you are better off writing the number as text to the direct ByteBuffer which will be written to the device where the text will be going. This creates no objects at all and is clearly OTT for 99% of use cases.

 

From http://vanillajava.blogspot.com/2012/01/stringvalueofint-vs-int.html

Published at DZone with permission of Peter Lawrey, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Sangjin Lee replied on Thu, 2012/01/19 - 1:07am

I don't understand why "" + i is more efficient (succinct?) for developers than String.valueOf(i). Care to elaborate? To me, the meaning of String.valueOf(i) couldn't be clearer. "" + i to me feels like using a clever trick. 

Michal Xorty replied on Thu, 2012/01/19 - 2:03am

For me "" + i looks like some smelly code of inexperienced programmer with poor Java core API konwledge.

Kari Ikonen replied on Thu, 2012/01/19 - 2:38am in response to: Michal Xorty

Actually for me, assumption that valueOf is always faster than "" is clear indication of novice java programmer.

Reason: novice does not realize what happens when int is actually constant. In such case "" trick is infinitely times faster since compiler resolves it at compile time. For valueOf, compiler can never perform such optimization. i.e. not fully understanding how core java works :)

André Pankraz replied on Thu, 2012/01/19 - 3:16am

Hmmm...I like your articles but I'm not with this one.

 String.valueOf or Integer.toString in bytecode:

 iload_2 [i]
 invokestatic java.lang.String.valueOf(int) : java.lang.String [43]
 astore 5 [s0]

 

 "" + i in bytecode:

 new java.lang.StringBuilder [52]
 dup
 invokespecial java.lang.StringBuilder() [54]
 ioad_2 [i]
 invokevirtual java.lang.StringBuilder.append(int) : java.lang.StringBuilder [55]
 invokevirtual java.lang.StringBuilder.toString() : java.lang.String [59]
 astore 7 [s2]

 

Maybe you should also observe your Garbage Collector and CPU ressources.

It may not be this interesting for such microbenchmarks, but in a GC heavy system such stuff sums up, needs more bytecode / class load space etc.

 

 

 

 

AND...

 

it's ugly!

Next article: Why "".equals(s) is better than s.isEmpty() - no!

 

Nice articles though!

Nigel Maddocks replied on Thu, 2012/01/19 - 4:24am

""+i  for me.

in fact I'd prefer just

i

If the compiler turns it into lengthy byte code then perhaps the compiler should recognise this as a common construct and do it better.  I prefer to be able to see my variable names rather than seek them out from a maze of [unnecessary] classes and methods.  Similarly I prefer my brake pedal to be obvious rather than having to find it among a maze of cables and levers.

Arnaud Des_vosges replied on Thu, 2012/01/19 - 5:14am

The problem with ""+i is that it is almost a silent conversion from int to String and it's not a good thing in a statically typed language.
See for instance: http://cyrille.martraire.com/2010/01/the-string-obsession-anti-pattern/
I think that the (relative) verbosity of String.valueOf(i) is almost welcome because it makes that kind of conversion explicit.

As for performance, the JVM could probably optmize both syntaxes to the same level, but it's natural that valueOf() is faster because it's just the raw conversion, probably inlined by the JIT, so it's generic optimization, no special pattern to detect. (Note that most advanced optimisations are done at runtime by the JVM, not during compilation from source to byte code unlike C/C++ compilers.)

Fabien Bergeret replied on Thu, 2012/01/19 - 11:50am

""+i convert an integer to a String by side-effect. It's so unexplicit that it should not be used. On the other hand, valueOf is perfectly understandable, despite a verbose syntax.

In this article, there are two points that are considered:
1) code effectiveness
2) coding effectiveness

I'm afraid there is another one, which is really important, and generally forgotten:
3) maintenance effectiveness

What I mean is that ""+i being more complex to read and understand that valueOf (even is faster to write), the code will more costly to maintain.

In my company, the Java ternary operator (?:) has been banned because of its non-readability, and on my projects, I've also banned the ""+i pattern. 

 

Dapeng Liu replied on Thu, 2012/01/19 - 11:01pm

IMO
the following codes are equally readable

String s = "" + i;
String s = String.valueOf(i);


it comes even more natural when there are alot of concatenations

String date = "" + yyyy + "/" + mm + "/" + dd + " " + mi + ":" + ss;

in this case I am afraid the 2nd form becomes much unreadable

String date = String.valueOf(yyyy) + "/" + String.valueOf(mm) + "/" + String.valueOf(dd) + " " + String.valueOf(mi) + ":" + String.valueOf(ss);

and if your line-width setting is 80 to 120, then too bad, the 2nd form needs to wrap anther line

well you would probably argue that String.format should be used, yes, it is much more preferable, then we back to the simple conversion statements and they are equally readable again ...

Peter Lawrey replied on Mon, 2012/01/30 - 11:12am in response to: Sangjin Lee

Is it faster to write and pure java without resorting to an API.

Peter Lawrey replied on Mon, 2012/01/30 - 11:14am in response to: Michal Xorty

I would give you more credit if you could say which API actually does the real work. (hint: its not String.valueOf()).

Peter Lawrey replied on Mon, 2012/01/30 - 11:17am in response to: André Pankraz

Thank you.  As I point out, if you really care about GC, you wouldn't be creating any garbage at all.  I didn't state how as it is achieved as it is covered in other articles.  A half way solution doesn't appear to be ideal. (creating slightly less objects instead of no objects)

Peter Lawrey replied on Mon, 2012/01/30 - 11:22am in response to: Fabien Bergeret

I can understand wanting to ban it.  I wonder if you also ban the following...

String id = "word" + i;

String id = "app" + i;

String id = "id" + i;

String id = "I" + i; 

String id = "" + i; 

IMHO, For consistency you should really ban them all or none.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.