加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 为什么map {} .compact比each_with_object([])更快?

发布时间:2020-12-17 03:57:16 所属栏目:百科 来源:网络整理
导读:我做了一些基准测试: require 'benchmark'words = File.open('/usr/share/dict/words','r') do |file| file.each_line.take(1_000_000).map(:chomp)endBenchmark.bmbm(20) do |x| GC.start x.report(:map) do words.map do |word| word.size if word.size 5
我做了一些基准测试:

require 'benchmark'

words = File.open('/usr/share/dict/words','r') do |file|
  file.each_line.take(1_000_000).map(&:chomp)
end

Benchmark.bmbm(20) do |x|
  GC.start
  x.report(:map) do
    words.map do |word|
      word.size if word.size > 5
    end.compact
  end

  GC.start
  x.report(:each_with_object) do
    words.each_with_object([]) do |word,long_sizes|
      long_sizes << word.size if word.size > 5
    end
  end
end

输出(ruby 2.3.0):

Rehearsal --------------------------------------------------------
map                    0.020000   0.000000   0.020000 (  0.016906)
each_with_object       0.020000   0.000000   0.020000 (  0.024695)
----------------------------------------------- total: 0.040000sec

                           user     system      total        real
map                    0.010000   0.000000   0.010000 (  0.015004)
each_with_object       0.020000   0.000000   0.020000 (  0.024183)

我无法理解它,因为我认为each_with_object应该更快:它只需要1个循环和1个新对象来创建一个新数组,而不是2个循环和2个新对象,以防我们组合map和compact.
有任何想法吗?

解决方法

阵列#<<如果原始内存空间没有足够的空间来容纳新项目,则需要重新分配内存.见 the implementation,特别是这一行

VALUE target_ary = ary_ensure_room_for_push(ary,1);

虽然Array#map不必重新分配内存,因为它已经知道结果数组的大小.特别参见the implementation

collect = rb_ary_new2(RARRAY_LEN(ary));

它分配与原始数组相同大小的内存.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读