4

I have an integer let say, int a = 123;

Now, I can convert it to String using below two ways:

1. Integer.toString(a)
2. String.valueOf(a)

I want to know, if there is any performance difference between the above two ways, let say when we are doing this for 10k integers or more and if yes then why?

Praveen Kishor
  • 2,413
  • 1
  • 23
  • 28
  • 1
    Test it using [JMH](https://openjdk.java.net/projects/code-tools/jmh/). – Johannes Kuhn Mar 29 '20 at 04:32
  • 1
    Does this answer your question? [Integer.toString(int i) vs String.valueOf(int i)](https://stackoverflow.com/questions/3335737/integer-tostringint-i-vs-string-valueofint-i) – Locke Mar 29 '20 at 04:52

3 Answers3

5

String.valueOf(int) internally calls the Integer.toString(int). So there will not be any performance difference. Or theoretically Integer.toString should be better as 1 less call.

vins
  • 15,030
  • 3
  • 36
  • 47
2

Below is the source for both method as of JDK 8

This is the source for Intger.toString()

 public static String toString(int i) {
    if (i == Integer.MIN_VALUE)
        return "-2147483648";
    int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
    char[] buf = new char[size];
    getChars(i, size, buf);
    return new String(buf, true);
}

And this is the source for String.valueOf(int)

public static String valueOf(int i) {
return Integer.toString(i);
}

As you can see there will be barely any difference in the performance , Integer.toString() is called in both cases

But I you have to choose one then the answer is Integer.toString() because that way i can reduce the overhead of calling String.valueOf(int) it will be barely anything , but as you may know a method call involves many things like putting method call on stack , saving state and control return position , then poping it off the stack , that all will be avoided, but still computers are too fast so it doesn't count

Abhinav Chauhan
  • 1,304
  • 1
  • 7
  • 24
1

The performance should be nearly identical because String.valueOf(a) is defined as follows:

public static String valueOf(int i) {
    return Integer.toString(i);
}

It also goes to reason that Integer.toString would be faster since it can skip String.valueOf on the call stack, but I don't know if the difference is enough to notice in practice.

Unfortunately java does not normally inline function calls so at a minimum it will need to spend extra time loading the function, but after the first call the CPU cache would likely make the redirect nearly unnoticeable.

Edit: You can find this on your own by using go to definition in your IDE. I was able to get this code snippit by selecting the function call and pressing Ctrl + B in Intellij Idea.

Locke
  • 7,626
  • 2
  • 21
  • 41