File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Performance and the fly likes Integer.toString(i) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Performance
Bookmark "Integer.toString(i)" Watch "Integer.toString(i)" New topic


Kris Reid
Ranch Hand

Joined: Jan 05, 2005
Posts: 247
Which method is more efficient to get a String from and int

"" + 5;


Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

It depends. Do you really mean '5', or a variable holding 5? If you really mean a literal, then "" + 5 will be evaluated at compile time to be "5", so it will be more efficient than Integer.toString(5) which has to do the conversion at runtime.

But if we're talking about a variable holding 5, then the opposite is true: at runtime there will be a StringBuffer to do the catenation, and that will be converted to a String, so the catenation version will do a lot more work.

But you really shouldn't be worrying about such little things, most of the time.

[Jess in Action][AskingGoodQuestions]
Kris Reid
Ranch Hand

Joined: Jan 05, 2005
Posts: 247

I'm writting a swing app that converts a heap of data and I am trying to get as much performance as possible.
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

Your best bet is going to be to write it in a way that is easy to read/maintain, and THEN use a profiler to see where the bottlenecks are. Often they are not where you think they'd be, and you end up spending a lot of time making minor improvements.

Using a profiler will show you exactly where you should be focusing your effort.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
I agree. Here's the link:
subject: Integer.toString(i)
jQuery in Action, 3rd edition