Friday, August 28, 2015

Battle of the Languages

One great thing about the challenges offered on CodeEval.com is that they can be solved in so many languages - e.g. choose the language of your choice and go at it! As a side benefit, one can easily compare run-times and memory footprints of languages by solving a challenge in many languages and viewing the results. As an experiment I did just that with the following challenge.

Here is the description of the challenge, as it can be seen on the site:



And the basic solution, which I implemented using the same basic algo in five languages (JavaScript, Java, PHP, C#, and C).

The test data is supplied via a file passed to args during execution, the same file is used in every execution run. JavaScript is run on Node. Execution takes place server side on a Linux based server (more details on the CodeEval site).

Basic algo is: for each line, split line on comma, parse each val to an int, run computation, print results to standard output.



Drum roll please....









As expected, C has the smallest mem usage and the fastest run-time, and by far at that. But I didn't expect Java to be that bad. Granted this is a trivial example. It would be interesting to see if the gap closes when the C program needs more supporting code. Educated guess is yes but not by much. The Java code for is below, I wonder if I'm doing anything wrong here or if it really is that less efficient in all ways.


import java.io.*;
public class Main {
    public static void main (String[] args) throws IOException {
        File file = new File(args[0]);
        BufferedReader buffer = new BufferedReader(new FileReader(file));
        String line;
        while ((line = buffer.readLine()) != null) {
            line = line.trim();
            String[] vals = line.split(",");
            int x = Integer.parseInt(vals[0]);
            int n = Integer.parseInt(vals[1]);
            compute(x,n);
        }
    }
    
    static void compute(int x, int n)
    {
        int m = n;
        while(m<x){
            m+=n;
        }
        System.out.print(m+"\n");
    }
}

I plan on doing this same test in Ruby, Python, and GO to do an even broader comparison, when I have some time. Results will follow if I do.

1 comment:

  1. I agree with a lot of the points you made in this article. If you are looking for the DBMS Tutorial, then visit TutorialCup. I appreciate the work you have put into this and hope you continue writing on this subject.

    ReplyDelete