红宝石阵Concat的相对速度+? [英] Ruby Array concat versus + speed?

查看:94
本文介绍了红宝石阵Concat的相对速度+?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了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 and concat() 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), while concat only appends the new element.

这篇关于红宝石阵Concat的相对速度+?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆