String.valueOf(int) vs "" + int
Join the DZone community and get the full member experience.
Join For Free
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 usThis 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
Opinions expressed by DZone contributors are their own.
Comments