Skip to content

Instantly share code, notes, and snippets.

@tlazaro
Created December 30, 2011 15:48
Show Gist options
  • Save tlazaro/1540368 to your computer and use it in GitHub Desktop.
Save tlazaro/1540368 to your computer and use it in GitHub Desktop.
My implementation of a Scala speed test
package mathtree
object ScalaNew {
sealed trait Term
case class Number(value: Int) extends Term
sealed trait Operator extends Term
case object Add extends Operator
case object Subtract extends Operator
case object Multiply extends Operator
case object Divide extends Operator
sealed trait Expression
case class SimpleExpr(value: Int) extends Expression
case class ComplexExpr(op: Operator, op1: Expression, op2: Expression) extends Expression
def main(args: Array[String]): Unit = {
val start_time = System.nanoTime()
var result : Int = 0
for(i <- 1 to 2000) {
result = calculate(make_expr(make_terms(args)))
}
val end_time = System.nanoTime()
println("Scala new\ttime = " + (end_time - start_time)/1000000L + "\tresult = " + result)
}
def make_terms(args: Array[String]) : Array[Term] = {
args.map {_ match {
case "+" => Add
case "-" => Subtract
case "x" => Multiply
case "/" => Divide
case n => Number(n.toInt)
}}
}
def make_expr(terms: Array[Term]): Expression = {
val stack = new scala.collection.mutable.Stack[Expression]
terms foreach { _ match {
case op: Operator => stack.push(ComplexExpr(op, stack.pop(), stack.pop()))
case n: Number => stack.push(SimpleExpr(n.value))
}}
stack.pop()
}
def calculate(expr: Expression): Int = expr match {
case simple: SimpleExpr => simple.value
case complex: ComplexExpr => complex.op match {
case Add => calculate(complex.op2) + calculate(complex.op1)
case Subtract => calculate(complex.op2) - calculate(complex.op1)
case Multiply => calculate(complex.op2) * calculate(complex.op1)
case Divide => calculate(complex.op2) / calculate(complex.op1)
}
}
}
@dcsobral
Copy link

dcsobral commented Jan 2, 2012

You should have used case objects instead of case classes for operators.

@tlazaro
Copy link
Author

tlazaro commented Jan 2, 2012

Done! Thanks Daniel!

I noticed quite an improvement on performance. It now takes an average of 35ms instead of 40ms on my machine. (After several runs from within SBT)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment