I'm assuming there that your profiler has identified this as a hotspot :)
Your problem, as you correctly infer, is the for-comprehension which adds an extra level of indirection for each time through the loop. The cost of this will be negligible for just 4 passes, but I can see that the method calls itself recursively...
What I wouldn't do is start by attempting to refactor to use tail-recursion, you have two better options you can try first:
Change the
foreach
to a for-comprehension then compile with theoptimize
flag, this should cause the compiler to emit awhile
loop.If that doesn't help, convert the comprehension to a
while
loop by hand.
Then... and only then, you might want to try tail recursion to see if it's faster than the while loop. Chances are that it won't be.
UPDATE
I was heading towards Petr's solution anyway :)
So here's the full thing tidied up to be a bit more idiomatic:
private def carve2(x: Int, y: Int) {
carve2(List((x, y)))
}
@tailrec private def carve2(coords: List[(Int,Int)]) = coords match {
case (x,y) :: rest =>
val rand: Int = random.nextInt(4)
//note that this won't necessarily yield four pairs of co-ords
//due to the guard condition
val add = for {
i <- 1 to 4
(x1, y1, x2, y2) = randomize(x, y, (i + rand) % 4)
if canUpdate(x1, y1, x2, y2)
} yield {
maze(y1)(x1) = 0
maze(y2)(x2) = 0
(x2, y2)
}
// tail recursion happens here...
carve2(rest ++ add)
case _ =>
}