Recently, while reviewing some legacy code I discovered a trick a developer had used to convert an integer to a string. The developer did this because the function only accepted a string as a parameter. As developers, often we look for succinct ways to code thinking that less code is faster. The interesting thing about the code is that it was the slowest of all the tests I had done. In all my efforts, I found five different ways to code to a conversion of an integer to a string.
1000 Iterations
The five different versions of the conversion are below with the slowest one first. The variable i is a native int. And the results were quite shocking. And surprising. Everything was tested at 1000 iterations.
"" + i
The above code is compiled by javac to use the StringBuilder class was two appends. One for the string and one for the int. I was surprised that the compiler implemented the append for an empty string.
Integer.toString(i)
This version of a call to the Integer class, which I thought should have been the conversion king was really slow. Particularly when static methods are supposed to be faster than instance methods.
i + ""
The above code is essentially the reverse of the other version but oddly is much faster. Sometimes twice as fast.
StringBuilder().append(i).toString()
I was quite surprised to see that StringBuilder with the single append was the fastest by a wide margin. It was actually almost twice as fast as Integer.toString(i). The append method uses the Integer.getChars() method to do its dirty work.
new Integer(i).toString()
This version of the conversion using the Integer class was the fastest. It was a bit faster than the string builder version above. Which may I state makes the exact same calls as first Integer version of the call.
100,000 Iterations
When the iterations are cranked up to 100,000 everything swings around. The JIT inlines a lot of the calls improving performance considerably. And in this case, the single StringBuilder append call won by a wide margin. Again, the results are sorted slowest to fastest.
// Slowest code "" + i new Integer(i).toString() Integer.toString(i) i + "" StringBuilder().append(i).toString() // Fastest code
Of course, these findings are wholly subjective. They’re run from within Git BASH in a Windows 10 environment. But the results are still interesting, none-the-less.