红宝石阵Concat的相对速度+? [英] Ruby Array concat versus + speed?
问题描述
我做了Ruby的阵列小的性能测试 CONCAT()
VS +
运行和 CONCAT()
是太快了。
然而,我不是为什么 CONCAT()
是如此之快?
谁能帮助吗?
这是code我用:
T = Time.now
AR = []
因为我在1..10000
AR = AR + [4,5]
结束
提出时间++(Time.now - T).to_s
T = Time.now
AR = []
因为我在1..10000
ar.concat([4,5])
结束
提出时间CONCAT+(Time.now - T).to_s
按照红宝石文档,所不同的是:
阵列#+
串联 - 返回由两个数组串联起来,以产生第三阵列建立了一个新的数组
。
块引用>阵列#CONCAT
阵列#CONCAT:追加的other_ary元素自
块引用>所以
+
运营商将在每次调用时(这是昂贵的)创建一个新的数组,而CONCAT
只追加了新的元素。I did small performance test of Ruby's array
concat()
vs+
operation andconcat()
was way too fast.I however am not clear on why
concat()
is so fast?Can anyone help here?
This is the code I used:
t = Time.now ar = [] for i in 1..10000 ar = ar + [4,5] end puts "Time for + " + (Time.now - t).to_s t = Time.now ar = [] for i in 1..10000 ar.concat([4,5]) end puts "Time for concat " + (Time.now - t).to_s
解决方案According to the Ruby docs, the difference is:
Array#+ :
Concatenation — Returns a new array built by concatenating the two arrays together to produce a third array.
Array#concat :
Array#concat : Appends the elements of other_ary to self.
So the
+
operator will create a new array each time it is called (which is expensive), whileconcat
only appends the new element.这篇关于红宝石阵Concat的相对速度+?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!