Scala:将元素附加到数组的最佳方法是什么? [英] Scala: what is the best way to append an element to an Array?
问题描述
假设我有一个 Array[Int]
之类的
Say I have an Array[Int]
like
val array = Array( 1, 2, 3 )
现在我想在数组中附加一个元素,比如值 4
,如下例所示:
Now I would like to append an element to the array, say the value 4
, as in the following example:
val array2 = array + 4 // will not compile
我当然可以使用 System.arraycopy()
并自行完成此操作,但必须有一个 Scala 库函数用于此目的,而我根本找不到.感谢您的指点!
I can of course use System.arraycopy()
and do this on my own, but there must be a Scala library function for this, which I simply could not find. Thanks for any pointers!
注意事项:
我知道我可以附加另一个元素数组,如下行所示,但这似乎太迂回了:
I am aware that I can append another Array of elements, like in the following line, but that seems too round-about:
val array2b = array ++ Array( 4 ) // this works
我了解 List 与 Array 的优缺点,出于各种原因,我特别对扩展 Array 感兴趣.
I am aware of the advantages and drawbacks of List vs Array and here I am for various reasons specifically interested in extending an Array.
编辑 1
感谢指向 :+
运算符方法的答案.这就是我一直在寻找的.不幸的是,它比使用 arraycopy
的自定义 append() 方法实现要慢——大约慢两到三倍.查看 SeqLike[]
中的实现,创建了一个构建器,然后将数组添加到其中,然后通过构建器完成追加,然后呈现构建器.不是一个好的数组实现.我做了一个比较两种方法的快速基准测试,查看十个周期中最快的时间.将单个项目附加到某个类 Foo
的 8 元素数组实例的 1000 万次重复使用 :+
需要 3.1 秒,使用简单的 需要 1.7 秒append()
方法使用 System.arraycopy();
在 Long 的 8 元素数组上执行 1000 万次单项追加重复需要 2.1 秒,:+
和 0.78 秒,使用简单的 append()
方法.想知道这是否无法通过 Array
的自定义实现在库中修复?
Edit 1
Thanks for the answers pointing to the :+
operator method. This is what I was looking for. Unfortunately, it is rather slower than a custom append() method implementation using arraycopy
-- about two to three times slower. Looking at the implementation in SeqLike[]
, a builder is created, then the array is added to it, then the append is done via the builder, then the builder is rendered. Not a good implementation for arrays. I did a quick benchmark comparing the two methods, looking at the fastest time out of ten cycles. Doing 10 million repetitions of a single-item append to an 8-element array instance of some class Foo
takes 3.1 sec with :+
and 1.7 sec with a simple append()
method that uses System.arraycopy();
doing 10 million single-item append repetitions on 8-element arrays of Long takes 2.1 sec with :+
and 0.78 sec with the simple append()
method. Wonder if this couldn't be fixed in the library with a custom implementation for Array
?
为了它的价值,我提交了一张票:https://issues.scala-lang.org/browse/SI-5017
For what it's worth, I filed a ticket: https://issues.scala-lang.org/browse/SI-5017
推荐答案
您可以使用 :+
将元素附加到数组,并使用 +:
附加它:>
You can use :+
to append element to array and +:
to prepend it:
0 +: array :+ 4
应该产生:
res3: Array[Int] = Array(0, 1, 2, 3, 4)
它与 Seq
的任何其他实现相同.
It's the same as with any other implementation of Seq
.
这篇关于Scala:将元素附加到数组的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!