Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to convert an int to a String?

Tags:

java

string

Say I have:

int someValue = 42; 

Now I want to convert that int value to a String. Which way is more efficient?

// One String stringValue = Integer.toString(someValue);  // Two String stringValue = String.valueOf(someValue);  // Three String stringValue = someValue + ""; 

I am just curious if there is any real difference or one is better than the other?

like image 957
Ascalonian Avatar asked Mar 17 '09 12:03

Ascalonian


People also ask

Which is the easiest way to convert an integer to a string in C?

sprintf() Function to Convert an Integer to a String in C This function gives an easy way to convert an integer to a string. It works the same as the printf() function, but it does not print a value directly on the console but returns a formatted string.


2 Answers

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 
like image 60
cobbal Avatar answered Oct 14 '22 11:10

cobbal


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.

like image 38
David Hanak Avatar answered Oct 14 '22 09:10

David Hanak