Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy's Java in this case faster (and slower) than C?
    primarykey
    data
    text
    <p>Some fellow just started learning C by reading K&amp;R and came up with its fahrenheit-to-celcius conversion loop printed down on the first pages:</p> <pre><code>#include &lt;stdio.h&gt; main () { int fahr; for (fahr = 0; fahr&lt;= 200000000; fahr = fahr + 20) printf("%d\t%6.2f\n", fahr, (5.0 / 9.0) * (fahr-32)); } </code></pre> <p>He was told Java to be slow. So, told him that Java's very competitive these days but that C will in this simple case probably be faster. Wanted to proof him and basically added "System.out." in front of printf().</p> <p>It was more than 10x slower. Way too much. I was baffled. Thought about String object creation, GC, -server, yada, yada, yada.</p> <p>I was even more baffled when I figured out that nearly 100% of the time was actually spent in printf() (<code>PrintSteam.write()</code>, output piped to /dev/null).</p> <p>After some fiddling I came up with this (doesn't do %f's rounding for now):</p> <pre><code>public static void main(String... args) throws Exception { int fahr=0; PrintWriter out = new PrintWriter(Channels.newWriter(Channels.newChannel(System.out), "US-ASCII") ); int max = 2000000000; for (fahr = 0; fahr&lt;= max; fahr = fahr + 20) // out.printf("%d\t%6.2f\n", fahr, (5.0 / 9.0) * (fahr-32)); out.println( fahr + "\t" + f(((5.0 / 9.0) * (fahr-32)) )); out.close(); } private static final String f(double d) { return (int)d + "." + (int)((d - (int)d)*100); } } </code></pre> <p>So, this uses NIO. And it <strong>outperforms</strong> gcc -O2 on two machines tested.</p> <p>Questions:</p> <ul> <li>why is the literal transscript from C to Java (i.e. <code>PrintStream</code>) <strong>so</strong> slow?</li> <li>(why is commented <code>out.printf()</code> so slow [maybe performance degrades over time]?)</li> <li>and finally: why is my solution faster than C (incl. JVM startup time)?</li> </ul>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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