On Thu, May 2, 2013 at 7:25 AM, Sasha Pachev <[email protected]> wrote:

> OK, the gauntlet has been thrown.
>
> http://asksasha.com/strrev.c
>
> coded in 25 minutes. When compiled with -O3 gives me this on my laptop:
>
> bash-4.1$ time ./strrev /usr/share/dict/words > /dev/null
>
> real    0m0.055s
> user    0m0.053s
> sys    0m0.002s
>

I think you're missing the point Sasha.  Your programs starts, performs a
function, and then exits in less than a second.  It's very fast, kudos to
you, but that's not going to give a JIT enough time to optimize the code
paths and outperform the C code.  If we were performing a more
sophisticated task over a longer period of time (think application server),
then Java will almost always out perform C/C++ -- sometimes by quite a
large margin.

Nevertheless, here is a Java version of the program:
import java.io.BufferedReader;
import java.io.FileReader;

public class LineReverse {
    public static void main(String... args) throws Exception {
        StringBuilder sb = new StringBuilder(1000);
        String filename = (args.length > 0) ? args[0] :
"/usr/share/dict/words";
        BufferedReader in = new BufferedReader(new FileReader(filename));
        String line;
        while ((line = in.readLine()) != null) {
            sb.setLength(0);
            sb.append(line);
            sb.reverse();
            System.out.println(sb);
        }
    }
}

On my machine:
real 0m0.706s
user 0m0.741s
sys 0m0.202s

The numbers look bad right?  That's because the majority of the time is
spent getting the JVM up and going...  Still it runs in a sub-second time
frame and it took me 3 minutes to write.

-Bryan

/*
PLUG: http://plug.org, #utah on irc.freenode.net
Unsubscribe: http://plug.org/mailman/options/plug
Don't fear the penguin.
*/

Reply via email to