What is the most efficient way to convert an int to a String?
tested it for 10m assignments of the number 10
One:
real 0m5.610s
user 0m5.098s
sys 0m0.220s
Two:
real 0m6.216s
user 0m5.700s
sys 0m0.213s
Three:
real 0m12.986s
user 0m11.767s
sys 0m0.489s
One seems to win
Edit: JVM is standard '/usr/bin/java' under Mac OS X 10.5
java version "1.5.0_16" Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b06-284) Java HotSpot(TM) Client VM (build 1.5.0_16-133, mixed mode, sharing)
More edit:
Code as requested
public class One {
public static void main(String[] args) {
int someValue = 10;
for (int i = 0; i < 10000000; i++) {
String stringValue = Integer.toString(someValue);
}
}
}
case 2 and 3 similarly
run using
javac *.java; time java One; time java Two; time java Three
Even though according to the measurements of cobbal, #1 seems to be the fastest, I'd strongly recommend the usage of String.valueOf()
. My reason for that is that this call does not explicitly contain the type of the argument, so if later on you decide to change it from int to double, there is no need to modify this call. The speed gain on #1 compared to #2 is only minimal, and as we all know, "premature optimization is the root of all evil".
The third solution is out of the question, since it implicitly creates a StringBuilder
and appends the components (in this case, the number and the empty string) to that, and finally converts that to a string.