简体   繁体   English

Scala数组尾部函数的性能

[英]Performance of tail function for Scala Arrays

Scala docs says that the performance of tail for an Array sequence is Linear while head performance is Constant . Scala文档说,数组序列的尾部性能是线性的,头部性能是常量 Since the whole block that contains array elements is brought to cache, I don't expect to see any difference between head and tail for an array. 由于包含数组元素的整个块被带到缓存中,我不希望看到数组的头部和尾部之间有任何差异。 I appreciate if someone explains why tail performance for arrays in Scala is linear. 如果有人解释为什么Scala中的数组的尾部性能是线性的,我感谢。

The tail function creates a new array containing all of the elements except the first. tail函数创建一个包含除第一个元素之外的所有元素的新数组。 To do this we need to create a copy of the array (minus the first element), which is a linear time operation. 为此,我们需要创建一个数组副本(减去第一个元素),这是一个线性时间操作。 As the array gets larger there is more to copy. 随着阵列变大,复制更多。

Use List instead if you require efficient head and tail operations. 如果您需要有效的头部和尾部操作,请使用List

You may be confusing tail with last 你最后可能会混淆尾巴

  • head gets the first element: O(1) for List and Array head获取第一个元素:List和Array的O(1)
  • last gets the last element: O(n) for List, O(1) for Array last获取最后一个元素:List的O(n),Array的O(1)
  • tail gets everything except the first: O(1) for List, O(n) for Array tail获取除第一个之外的所有内容:List的O(1),Array的O(n)
  • init gets everything except the last: O(n) for List and Array init获取除最后一个之外的所有内容:列表和数组的O(n)

There is a pretty big difference between lists and arrays . 列表数组之间存在很大差异。 head and tail are the canonical interface to lists, which in Scala, are singly linked lists. headtail是列表的规范接口,在Scala中是单链接列表。 head refers to the first thing in the list and tail refers to all of the elements after the first. head指的是列表中的第一个东西, tail指的是第一个之后的所有元素。 Since linked lists implement the tail as a pointer, this operation is a constant time operation. 由于链接列表将尾部实现为指针,因此该操作是恒定时间操作。

However, things are a little different for arrays. 但是,对于数组而言,情况有所不同。 Arrays are used for fast random access and refers to a contiguous block of memory. 数组用于快速随机访问,指的是连续的内存块。 Scala still exposes the list-like interface of head and tail , but it has to do things a little differently to simulate that. Scala仍然暴露了headtail的类似列表的界面,但它必须做一些不同的事情来模拟它。 In order to simulate tail , it has to make a new array containing all elements except the first. 为了模拟tail ,它必须创建一个包含除第一个之外的所有元素的新数组。 It has to copy all of its values into a new array, which is a linear time operation. 它必须将所有值复制到一个新的数组中,这是一个线性时间操作。

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

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