Why Scala's foldLeft has lower performance than iterating with an index on strings?

Viewed 1844

I am comparing the performance of two atoi implementations. The first is iterating on the input string getting chars using charAt; the second is using foldLeft.

object Atoi {
  def withRandomAccess(str: String, baze: Int): Int = {
      def process(acc: Int, place: Int, str: String, index: Int): Int = 
        if (index >= 0) process(acc + value(str.charAt(index)) * place, place * baze, str, index-1) else acc
      process(0, 1, str, str.length - 1)
    }

  def withFoldLeft(str: String, base: Int): Int = (0/:str) (_ * base + value(_))

  def value(c: Char): Int = { /* omitted for clarity */ }

  def symbol(i: Int): Char = { /* omitted for clarity */ }
}

The foldLeft version is 2x to 4x slower (the complete benchmark code is here). I didn't expect this. Do you know why? Is Scala converting the string to a List before processing it? Do you have a hint on how to boost foldLeft performance on strings?

1 Answers
Related