Which one of the following ways is faster? and what is the difference(s)?
int i=0x10;
String s=i+"";
String s1=Integer.toString(i);
String s2=String.valueOf(i);
I don't know if there is another way or not.
Thanks in advance.
Which one of the following ways is faster? and what is the difference(s)?
int i=0x10;
String s=i+"";
String s1=Integer.toString(i);
String s2=String.valueOf(i);
I don't know if there is another way or not.
Thanks in advance.
Which one of the following ways is faster? and what is the difference(s)?
Take a look at the implementation of String.valueOf(int)
(in hyperlinked Grepcode format):
2942 public static String valueOf(int i) {
2943 return Integer.toString(i, 10);
2944 }
This should give you a hint—especially if you are familiar with the concept of method call inlining performed routinely by the JIT compiler on static
method calls.
On the topic of proper microbenchmarking, you should use jmh
to execute this:
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
@OperationsPerInvocation(1)
@Warmup(iterations = 5, time = 200, timeUnit=MILLISECONDS)
@Measurement(iterations = 30, time = 200, timeUnit=MILLISECONDS)
@State(Scope.Thread)
@Threads(1)
@Fork(1)
public class Measure
{
private int arg;
@Setup public void setup() {
arg = (int) System.nanoTime();
}
@GenerateMicroBenchmark public String integerToString() {
return Integer.toString(arg);
}
@GenerateMicroBenchmark public String stringValueOf() {
return String.valueOf(arg);
}
@GenerateMicroBenchmark public String plus() {
return ""+arg;
}
}
These were my results:
Benchmark Mode Samples Mean Mean error Units
o.s.Measure.integerToString avgt 30 53.023 8.868 ns/op
o.s.Measure.plus avgt 30 54.043 6.833 ns/op
o.s.Measure.stringValueOf avgt 30 52.071 8.217 ns/op
String s1=Integer.toString(i);
String s2=String.valueOf(i);
In the above two Integer.toString() will be fast as String.valueOf(i) will call the Integer.toString() method to convert.Below is the implementation of toString method
public static String valueOf(int i) {
return Integer.toString(i);
}
String s=i+"";
In this case first i will be converted into string then it will be appended to string, So already one conversion of i to string ,Then again concatenation, So it will be slowest compared to the other two options.
String s2=String.valueOf(i);
This calls Integer.toString(i, 10);
so it will be slower than direct call to Integer.toString(i);
Finally, comparatively faster will be Integer.toString(i);