1

I've got quick question. Why is Javascript almost twice as fast as Java code in this snippet? Java code:

public class Main{

  public static void main(String[] args){
        long startTime = System.currentTimeMillis();
        double sum = 0.0;
        for(double i=1; i<=100000; i++){
            for(double j=1; j<=10000; j++){
                sum += i/j;
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println(sum + " [" + (endTime-startTime) + "ms]");
    }
}

Javascript code:

console.time("func");

console.log(func());

console.timeEnd("func");

function func(){
    let sum = 0.0;
    for(let i=1; i<=100000; i++){
        for(let j=1; j<=10000; j++){
            sum += i/j;
        }
    }  
    return sum; 
}

Terminal screenshot

As I understand Java is supposed to be faster when it comes to calculations, so this is where java should beat node anytime. Can you give some examples as to where is java superior in terms of performance. Thanks

  • 5
    Micro-benchmarks like these are absolutely useless and don't prove anything (see also: https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java) – UnholySheep Dec 13 '18 at 18:24

1 Answers1

1

This isn't a particuarly realistic piece of code however, it appears Java is not loop unrolling the inner loop. I tried

        for(double j=1; j<=10000; j+=2){
            sum += i/j;
            sum += i/(j + 1);
        }

and it was twice as fast.

I suggest you try a more realistic example.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • I really don't get what are you pointing at, its basically the same code in both examples and its not supposed to be "realistic", its meant to compare performance with same code and no optimizations(other than what compiler does) – Pavle Vodopija Dec 13 '18 at 21:32
  • @PavleVodopija different compilers have different optimisations, like a cookbook of common recipes, they usually only have optimisations for common patterns, if you use an uncommon pattern it's pot luck as to whether someone has written an optimisation for it or not, and gives you no indication as to how it performs generally. – Peter Lawrey Dec 14 '18 at 08:33
  • @PavleVodopija it's like determining whether someone is a good programmer based on a question about Alan Tuning. A programmer is more likely to have heard of him, but not knowing who he is doesn't mean they are not a good programmer. – Peter Lawrey Dec 14 '18 at 08:34