简体   繁体   English

Scala标准库中ArrayBuffer实现的效率可能较低

[英]Possible inefficiency in the ArrayBuffer implementation in Scala standard library

While studying programming, I think I stumbled upon an inefficiency in Scala, given that the description in our material is correct. 鉴于我们材料中的描述是正确的,在学习编程时,我认为我偶然发现了Scala的效率低下。 The possibility for a lighter implementation was confirmed by a friend of mine who has got Silver and Bronze medals in International Olympiad in Informatics. 我的一个朋友证实了更轻松实施的可能性,他的朋友在国际信息学奥林匹克竞赛中获得了银牌和铜牌。

In our learning material it reads: "For example, for an ArrayBuffer it is very efficient to append elements at the end: as the internal array always doubles in size, the allocation of and copying to the new array occurs rather seldomly. In contrast, prepending an element at the beginning is time-consuming because a new internal array is allocated and the elements copied to it every time the method is called." 在我们的学习材料中,其内容为:“例如,对于ArrayBuffer,在末尾追加元素非常有效:由于内部数组的大小总是加倍,因此很少分配和复制到新数组。相反,在开始时在元素之前添加元素非常耗时,因为会分配一个新的内部数组,并且每次调用该方法时都会将元素复制到该元素。”

Couldn't there be another array storing the indices so that it would always add the elements to the end? 难道没有另一个数组存储索引,以便它总是将元素添加到末尾吗?

There could be a second array containing the indices, but it would be less efficient for a number of reasons: 可能会有第二个包含索引的数组,但是由于多种原因,效率会降低:

  1. The array of indices would require additional storage 索引数组将需要额外的存储

  2. Accessing an element would require at least two memory reads rather than one 访问一个元素至少需要两次内存读取,而不是一次

  3. If indices are not kept sorted then each access requires a search of the array of indices 如果索引未保持排序,则每次访问都需要搜索索引数组

  4. If the indices are kept sorted then you have exactly the same problem with this array that you were trying to avoid for the original array. 如果索引保持排序,则该数组将遇到与原始数组完全相同的问题。

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

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