Note that there are some explanatory texts on larger screens.

plurals
  1. POFastest way of converting integer to string in java
    text
    copied!<p>Everytime I had to convert an <code>int</code>into a <code>String</code> I picked either <code>""+a</code>or <code>Integer.toString(a)</code>. 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:</p> <pre><code>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; } </code></pre> <p>the output is:</p> <pre><code>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! </code></pre> <p>I think function_2 is so fast, because it is compiled as</p> <pre><code>public static void function_2() { j="1"; } </code></pre> <p>so to avoid that, I used the function <code>getOne()</code> instead. But here is the interesting part(for me): <code>function_3</code> must be compiled without using the original <code>toString</code> method of <code>Object</code>(in this case <code>Integer.toString(1)</code> because <code>int</code> is primitive). My question is: How does the compiler actually threat <code>""+1</code> so it is slower then calling <code>Integer.toString(1)</code>?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload