Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Optimization with Scala

What structures of Scala can be used more efficiently than in Java, to increase execution speed? I don't know if this is possible, but to clear my doubts :)

Thanks

like image 735
adelarsq Avatar asked Oct 19 '10 20:10

adelarsq


4 Answers

The scala @specialized annotation can generate multiple versions of a class, fine-tuned with specific primitive types. You can write all of that out in Java, but you probably don't want to.

like image 200
Ross Judson Avatar answered Oct 07 '22 01:10

Ross Judson


To expand on Ross's answer, you can use @specialized to generate specific versions of a collection. For instance, in Java you'd generally use fastutil or Apache Primitives for collections of primitives. Scala's @specialized will generate these variants for you and hide them automatically like so:

class MyLinkedList[@specialized T] (args: T*) {
  // whatever it does
}

Other than that, actors make it easier to write concurrent applications. Coming up in 2.9 are parallel collections, which can apply higher-order functions in parallel across collections, speeding up any place you'd have the Scala equivalent of a Java loop (fold, foreach, etc). See this ScalaDays talk for the nitty-gritty on this.

like image 37
Joshua Hartman Avatar answered Oct 07 '22 02:10

Joshua Hartman


As of 2.9, the parallel collections library is slated to be part of the standard distribution. This will allow extremely simple distribution of so-called "embarrassingly parallel" problems over multiple cores. Doing so in Java takes considerably more effort.

As a general rule, Scala benchmarks range from moderately slower than Java to slightly faster, depending on the problem and coding techniques.

like image 6
Dave Griffith Avatar answered Oct 07 '22 02:10

Dave Griffith


I'll refrain from speculation on how the resulting performance might differ from an equivalent Java construct, but Scala does closure elimination, which might make a measurable difference, modulo HotSpot tricks.

Also stay tuned for Iulian's thesis which should be out soon and will provide a lot more information on the subject of Scala optimization.

like image 2
Alex Cruise Avatar answered Oct 07 '22 02:10

Alex Cruise