简体   繁体   English

Scala中Array.map(f:A => B)的性能不佳

[英]Poor performance of Array.map(f: A => B) in Scala

Please can someone explain to me, why Array.map(f: A=> B) method is implemented in a such way that it is more than 5 times slower than this code: 请有人向我解释一下,为什么Array.map(f:A => B)方法的实现速度比这段代码快5倍以上:

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 trait, uses Scala 'for loop' for iterating over the elements of input Array object, which of course is much slower than using 'while loop'. Array类中的方法映射(f:A => B)由TraversableLike特性提供,它使用Scala'for循环'迭代输入Array对象的元素,这当然比使用'while循环慢得多”。

Scala version: 2.9.2 Java: jdk1.6.0_23 64bit windows Scala版本:2.9.2 Java:jdk1.6.0_23 64位窗口

map is a generic operation (and not specialized (yet)). map是一个通用操作(而不是专门的(还))。 So you have to box/unbox the operations on the way in and out of the function. 因此,您必须在进出函数的途中对操作进行装箱/取消装箱。 Unsurprisingly, it's much slower. 不出所料,它要慢得多。 This, rather than the style of loop used, is the culprit. 这不是使用的循环风格,而是罪魁祸首。

The reason it's done this way is for consistency and ease of maintenance of the code. 这样做的原因是为了保持代码的一致性和易维护性。 With infinite numbers of infinitely carefully people working on the code, each method would be hand-crafted for optimal speed while still being generic. 由于无数人无限精心处理代码,每种方法都是手工制作的,以获得最佳速度,同时仍然是通用的。 Generic utility has been favored over speed, as you can always get speed back by writing the while loop by hand, but if it's not generic and you need it to be, you're stuck. 通用实用程序一直受到速度的青睐,因为你可以通过手动编写while循环来获得速度,但是如果它不是通用的而你需要它,那么你就会被卡住。

Improving the performance of Scala with operations on primitive collections is a goal, but probably not the very top goal of the team working on Scala. 通过对原始集合进行操作来提高Scala的性能是一个目标,但可能不是使用Scala的团队的最高目标。 For now, if you need speed, use the while loop. 现在,如果您需要速度,请使用while循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM