Everytime I had to convert an intinto a String I picked either ""+aor Integer.toString(a). Now I wondered which way is faster, so I wrote a simple benchmark that calls function_1, function_2 and function_3 10000000 times and prints how long it takes to process the functions. Here are the functions:
public static String i="";
public static String j="";
public static String k="";
public static void function_1()
{
i=Integer.toString(getOne());
}
public static void function_2()
{
j=""+1;
}
public static void function_3()
{
j=""+getOne();
}
public static int getOne()
{
return 1;
}
the output is:
Benchmarking starting...
Executing function_1 10000000 time(s)...
Done executing function_1 in 476 ms.
Executing function_2 10000000 time(s)...
Done executing function_2 in 8 ms.
Executing function_3 10000000 time(s)...
Done executing function_3 in 634 ms.
Benchmarking complete!
I think function_2 is so fast, because it is compiled as
public static void function_2()
{
j="1";
}
so to avoid that, I used the function getOne() instead. But here is the interesting part(for me): function_3 must be compiled without using the original toString method of Object(in this case Integer.toString(1) because int is primitive). My question is: How does the compiler actually threat ""+1 so it is slower then calling Integer.toString(1)?
function_3uses aStringBuilderwhilefunction_1doesn't. And internally, theStringBuilderwill callString.valueOf().function_3is slower thanfunction_1. If you're wondering why it's "faster," stop wondering :-)javap -c MyClass