Every time I had to convert int to String , I chose either ""+a or Integer.toString(a) . Now I was wondering which path is faster, so I wrote a simple test that calls functions_1, function_2 and function_3 10,000,000 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; }
output:
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 compiled as
public static void function_2() { j="1"; }
therefore, to avoid this, I used the getOne() function instead. But here is the interesting part (for me): function_3 should be compiled without using the original toString Object method (in this case, Integer.toString(1) , because int is primitive). My question is: how does the compiler really threaten ""+1 , so is it slower than calling Integer.toString(1) ?
source share