Poor Array.map performance (f: A => B) in Scala

Please explain to me why the method Array.map (f: A => B) is implemented in such a way that it is more than 5 times slower than this code:

val list = Array(1, 2, 3, 4, 5, 6, 7, 8, 9) val newList = new Array[Int](size) var j = 0 while (j < size) { newList(j) = list(j) j += 1 } 

The method map (f: A => B) in the Array class, which is provided by TraversableLike, uses Scala 'for loop' to iterate over the elements of the input Array object, which, of course, is much slower than using the while loop.

Scala version: 2.9.2 Java: jdk1.6.0_23 64-bit windows

+7
source share
1 answer

map - a general operation (and not specialized (yet)). Thus, you must insert / remove operations along the path to and from the function. No wonder this is much slower. This, and not the style of the loop used, is the culprit.

The reason this is done is because the code is consistent and easy to maintain. With an infinite number of infinitely cautious people working on the code, each method would be manually created for optimal speed, but it would still be common. The universal utility was preferable to speed, since you can always get the speed back by writing a while loop manually, but if this is not common and you need it, you are stuck.

Improving Scala's performance through operations with primitive collections is the goal, but probably not the highest goal, of the Scala team. For now, if you need speed, use a while loop.

+14
source

All Articles