Why is map {} .compact faster than each_with_object ([])?

I did some tests:

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

Output (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)

I cannot understand this because I thought it each_with_objectshould be faster: it only needs 1 cycle and 1 new object to create a new array instead of 2 cycles and 2 new objects in the case when we combine mapand compact. Any ideas?

+4
source share
1 answer

Array#<<memory needs to be reallocated if there is not enough space in the original memory space to store the new item. See implementation , especially this line

VALUE target_ary = ary_ensure_room_for_push(ary, 1);

Array#map , . . ,

collect = rb_ary_new2(RARRAY_LEN(ary));

, .

+10

Source: https://habr.com/ru/post/1679965/


All Articles