贴出测试代码:
#for
def tfor
o = Time.now
(0..100000000).each do |i|
i
end
n = Time.now
puts "total cast time:#{n-o}"
end
#while
def twhile
o = Time.now
i=100000000
while (i>0)
i-=1
end
n = Time.now
puts "total cast time:#{n-o}"
end
tfor # total cast time:9.864268
twhile # total cast time:3.355015
如上面的输出结果,可见用 while 的比较的快。
不知道这样写是不是使用了 block
def tfor
o = Time.now
for i in 0..100000000
i
end
n = Time.now
puts "total cast time:#{n-o}"
end
#while
def twhile
o = Time.now
i=100000000
while (i>0)
i-=1
end
n = Time.now
puts "total cast time:#{n-o}"
end
total cast time:9.846828393 total cast time:3.756857119
还是 while 比较快!
ruby 2.0.0dev (2012-06-30 trunk 36257) [x86_64-linux]
total cast time:5.928291172
total cast time:2.927292006
ruby 1.8.7 (2011-02-18 patchlevel 334) [x86_64-linux], MBARI 0x6770, Ruby Enterprise Edition 2011.03
total cast time:12.951016
total cast time:19.63892
真的太烂了吧。。。我的机器开个 Netbeans 都卡还能跑成这样呢,没少零。
呃,,这结果对比也说明了不同 Ruby 实现哪个快是不一定的:-)
看来 Ruby 2 快了不少啊,的确是 1.8.7 比较慢的缘故
$ ruby -v
ruby 1.8.7 (2012-02-08 patchlevel 358) [x86_64-linux]