Skip to content

Instantly share code, notes, and snippets.

@robbypelssers
Last active December 19, 2015 18:38
Performance (Scala)
package performance
import java.util.Date
/**
* In this little demo we try to calculate the sum of a list of numbers (0,1,... ,1000.000)
* using various approaches. As we will see Java outperforms the Scala versions with just
* a few milliseconds at the expense of readability, maintainability and productivity.
*
* However, I noticed that passing a method instead of a function comes with a performance penalty.
* In that case the method is converted to a function using ETA expansion.
*/
object SumUp extends App {
val numbers = (0 to 1000000).toList
def sumJava(numbers: List[Int]):Int = {
var total = 0
for (number <- numbers) {
total = total + number
}
total
}
def sumScala1(numbers: List[Int]):Int = numbers.foldLeft(0)((a,b) => a + b)
def sumScala2(numbers: List[Int]):Int = numbers.foldLeft(0)(sum)
def sumScala3(numbers: List[Int]):Int = numbers.foldLeft(0)(sumAsFunction)
def sumScala4(numbers: List[Int]):Int = numbers.foldLeft(0)(new SumFunction)
def sum(a: Int, b: Int): Int = a + b
val sumAsFunction = sum _ //here we convert the method to a function
class SumFunction extends Function2[Int,Int, Int] {
def apply(a: Int, b: Int): Int = a + b
}
/**
* profile method works like an Around Advice in AspectOriented programming
*/
def profile[T](body: => T) = {
val start = new Date()
val result = body
val end = new Date()
println("Execution took " + (end.getTime() - start.getTime()) + " milliseconds")
result
}
profile(sumJava(numbers)) //using imperative Java
profile(sumScala1(numbers)) //using inline function
profile(sumScala2(numbers)) //using method
profile(sumScala3(numbers)) //using method converted to function before passing it to foldleft
profile(sumScala4(numbers)) //using a function class
}
/**
Execution took 14 milliseconds //using imperative Java
Execution took 17 milliseconds //using inline function
Execution took 95 milliseconds //using method
Execution took 17 milliseconds //using method converted to function
Execution took 18 milliseconds //using a function class
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment