2

In many websites I have studied that scala is faster than Java. I have written code to test the time difference between these two but Scala takes more time. I don't know whether I am making any mistake. Please correct me if I am wrong.

Scala code

package com.first

import java.util.ArrayList

object Word extends App{
  val absoluteResult = new ArrayList[Any]()
  val before = System.currentTimeMillis()
  var i =0
  while (i<10000) {
    i = i+1
    val result = List("foo", 23, true).iterator
    while (result.hasNext) {
      absoluteResult.add(foo(result.next))
    }
  }
  println("Took : "+(System.currentTimeMillis() - before)
      +" ms, number of elements : "+absoluteResult.size)

  def foo(obj : Any) =
    obj match {
          case _:String => "String"
          case _:Boolean => "Boolean"
          case _:Integer => "Integer"
          case _ => throw new IllegalArgumentException()
    }
}

output Took : 142 ms, number of elements : 30000

Java code

package com.first;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class quicksort {
    public static void main(String[] args) {
        List<Object> absoluteResult = new ArrayList<Object>();
        long before = System.currentTimeMillis();
        for (int i=0; i < 10000; i++) {
          List<Object> result = new ArrayList<Object>();
          result.add("foo");
          result.add( 23);
          result.add(true);
          for (Object y : result) {
            absoluteResult.add(foo(y));
          }
        }
        System.out.println("Took : "+(System.currentTimeMillis() - before)
          +" ms, number of elements : "+absoluteResult.size());
      }


    static String foo(Object s) {
      if (s instanceof String) {
        return "String";
      } else if (s instanceof Boolean) {
        return "Boolean";
      } else if (s instanceof Integer) {
        return "Integer";
      } else {
        throw new IllegalArgumentException();
      }
}
}

output Took : 30 ms, number of elements : 30000

Hoopje
  • 12,677
  • 8
  • 34
  • 50
Gowtham SB
  • 332
  • 1
  • 3
  • 16
  • i'm not saying which one is faster, but for meaningful tests you can try the java micro benchmark test which is used `for building, running, and analysing nano/micro/milli/macro benchmarks written in Java and other languages targetting the JVM.` http://openjdk.java.net/projects/code-tools/jmh/ – pezetem Oct 09 '15 at 12:14
  • 7
    "scala is faster than java" - this is not true in general for any kind of program. Also writing a correct micro-benchmark on the JVM is much harder than just writing a loop like you are doing, because of JIT optimization etc. See [How do I write a correct micro-benchmark in Java?](http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java) – Jesper Oct 09 '15 at 12:14
  • Do not be deterred by the no-meaningful-benchmark fraction: it is good to see comparative code. For now: Scala has the potential to be a bit better optimized for its Functional Programming data structures and algorithms (i.e. immutable data). But java might have a head start of being closer to the JVM (=uglier?), more human resources having dealt with the code. – Joop Eggen Oct 09 '15 at 12:46
  • Do a correct benchmark. I've moved your Scala code to a function, called it 4 times in a row, and the results were Took : 283 ms, number of elements : 30000 Took : 34 ms, number of elements : 30000 Took : 17 ms, number of elements : 30000 Took : 3 ms, number of elements : 30000 – Kolmar Oct 09 '15 at 13:20
  • Closed as a duplicate: even though code under inspection differs, both questions lack proper benchmarking and top answer by Shipilev is a great example how controversial "Scala is faster/slower than Java" question is. Also pay attention to a [relevant post](http://shipilev.net/blog/2014/java-scala-divided-we-fail/) and his blog overall – om-nom-nom Oct 09 '15 at 13:40

1 Answers1

9

Scala is not faster than Java (nor is Java faster than Scala).

Your "benchmark" is of poor quality, you should use JMH (http://openjdk.java.net/projects/code-tools/jmh/) or similar for doing microbenchmarks. Main reason is to eliminate dead code and to warm up the code. See http://java-performance.info/jmh/ and http://www.oracle.com/technetwork/articles/java/architect-benchmarking-2266277.html

Optimizations in Java are not done by the compiler but by the JVM (Hotspot for example). So its very unlikely that there are real performance differences between "bytecodes" generated by Scala/Java or Clojure compilers.

If you want to deep dive into this just analyze the bytecode (that is the .class file which you Java or Scala compiler produce) by using the Class File Disassembler

javap -c YourClass.class
salyh
  • 2,095
  • 1
  • 17
  • 31