Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance difference between Integer.toString() and String.valueOf()? [duplicate]

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?

like image 632
Praveen Kishor Avatar asked Oct 25 '25 05:10

Praveen Kishor


2 Answers

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.

like image 199
vins Avatar answered Oct 26 '25 18:10

vins


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

like image 31
Abhinav Chauhan Avatar answered Oct 26 '25 19:10

Abhinav Chauhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!