开发者社区 问答 正文

Ruby中的map和collect之间的区别?

我已经对此进行了Google搜索,并得到了片面的/矛盾的意见- 在Ruby / Rails中对数组执行a map和a 之间实际上有什么区别collect吗?

这些文档似乎没有任何建议,但是方法或性能上可能存在差异吗?

展开
收起
保持可爱mmm 2020-01-13 17:27:07 557 分享 版权
1 条回答
写回答
取消 提交回答
  • 我做了一个基准测试来尝试回答这个问题,然后找到了这篇文章,所以这是我的发现(与其他答案略有不同)

    这是基准代码:

    require 'benchmark'

    h = { abc: 'hello', 'another_key' => 123, 4567 => 'third' } a = 1..10 many = 500_000

    Benchmark.bm do |b| GC.start

    b.report("hash keys collect") do many.times do h.keys.collect(&:to_s) end end

    GC.start

    b.report("hash keys map") do many.times do h.keys.map(&:to_s) end end

    GC.start

    b.report("array collect") do many.times do a.collect(&:to_s) end end

    GC.start

    b.report("array map") do many.times do a.map(&:to_s) end end end

    我得到的结果是:

                   user     system      total        real
    

    hash keys collect 0.540000 0.000000 0.540000 ( 0.570994) hash keys map 0.500000 0.010000 0.510000 ( 0.517126) array collect 1.670000 0.020000 1.690000 ( 1.731233) array map 1.680000 0.020000 1.700000 ( 1.744398)

    也许别名不是免费的?

    问题来源于stack overflow

    2020-01-14 11:32:09
    赞同 展开评论
问答分类:
问答地址: