2
Integer.toString(int);

and

String.valueOf(int);

Which one among the above two methods is the efficient way of converting an int to String?

Thanks in advance.

Mudassir
  • 13,031
  • 8
  • 59
  • 87
  • 1
    It's hard to say which is more efficient, but the difference might be too small to care about. – euphoria83 Dec 10 '10 at 03:40
  • Same as [Integer.toString(int i) vs String.valueOf(int i) ](http://stackoverflow.com/questions/3335737/integer-tostringint-i-vs-string-valueofint-i)., which also has profiling results. – Matthew Flaschen Dec 10 '10 at 03:47

3 Answers3

8

String.valueOf calls Integer.toString, so I guess you could argue that Integer.toString is marginally more efficient.

EDIT: With a modern compiler the calls will be inlined so there should be no difference at all between the two. With an ancient compiler the difference should still be negligible.

Cameron Skinner
  • 51,692
  • 2
  • 65
  • 86
  • Yeah, I use Integer.toString(int); but today I saw String.valueOf(int); in other developer's code. And I was wondering whats the difference between the two. – Mudassir Dec 10 '10 at 03:44
  • 3
    http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java#String.valueOf%28int%29 for reference. – Mark Elliot Dec 10 '10 at 03:44
  • 1
    @Mudassir: In practice the difference will be completely negligible. The cost of a function call is extremely low, and in this case a decent compiler will probably optimise it away since `String.valueOf` is a one-line method that delegates to `Integer.toString`. – Cameron Skinner Dec 10 '10 at 03:45
  • @cameron for which implementation ? OpenJDK ? – euphoria83 Dec 10 '10 at 03:46
  • @Euphoria: I looked at the Sun Java 6 code, but @Mark's reference to OpenJDK has the same one-liner. – Cameron Skinner Dec 10 '10 at 03:48
  • @Cameron - unless you run this on a really old JVM, the HotSpot JIT **will** inline the call, making the two calls' performance identical. – Stephen C Dec 10 '10 at 04:27
  • @Stephen: Yes, I know. I mentioned that in my follow-up comment (albeit not as succinctly as you just put it). I've updated the answer to reflect this. – Cameron Skinner Dec 10 '10 at 04:29
2

I think that the String.valueOf() method was just provided for the purpose of flexibility, Since the purpose is closely related with String class(in fact for the conversion to String). While the (Integer/Float/etc).toString() method is the authentic method for the purpose of String conversion. You can refer them as slightly overloaded method.

Zaid
  • 21
  • 1
1

Actually it doesn't matter which method you use. But I think Integer.toString(int); is more efficient because, String.toString(int); is internally calling the same method.

Chromium
  • 1,073
  • 1
  • 9
  • 25