Saturday, June 4, 2016

JS Series: Node.js vs. Java Simple Speed Test

This evening after working through a few asynchronous and synchronous methods in node.js to process huge files I thought I would write the same simple math routine in JavaScript/node.js and again in Java. I have been impressed so far with the performance of node and my JS code. The fact that I am getting the speed I do and I get it with a save then run without compile has me convinced JS is a contender for my next time sensitive project.



--------------------------
Node/JavaScript 
--------------------------

var start = new Date();
var n = 1;
for (var i = 1 ; i <= 100000000 ; i++) {
    n = n + i;
}
var end = new Date();
var tm = end.getTime() - start.getTime();
console.log('tm->'+tm+'milliseconds');
console.log('n->'+n);



--------------------------
Java
--------------------------

import java.util.Date;
class Summer {
    public static void main(String[] args) {
        Date startDate = new Date();
        long n = 1;
        for (long i = 1 ; i <= 100000000 ; i++) {
            n = n + i;
        }
        Date endDate = new Date();
        long tm = endDate.getTime() - startDate.getTime();
        System.out.println("tm->" + tm + "milliseconds");
        System.out.println("n->"+n);
    }
}


Results

Minus the boilerplate class stuff in Java each of these are exactly 8 lines of code. So how did they do?

Davids-MacBook-Air:numbers dbell$ java Summer
tm->41milliseconds
n->5000000050000001
Davids-MacBook-Air:numbers dbell$ node summer.js
tm->139milliseconds

n->5000000050000001


The difference isn't drastic for such a simple example but Java runs in 1/3 the time and is our winner!

Enjoy!



No comments:

Post a Comment