ぬけラボ

φ(..)メモメモ

Ruby FiberとEnumerator

FiberとEnumeratorのメモ。
EnumeratorはFiberを使って実装されているらしい?
実行速度の比較をしてみた。

Fiber

words = Fiber.new do
  DATA.each do |line|
    line.scan(/\w+/) do |word|
      Fiber.yield word.downcase
    end
  end
  nil
end

counts = Hash.new(0)
while word = words.resume
  counts[word] += 1            
end

counts.keys.sort.each do |k|
  puts "#{k} : #{counts[k]}"
  #=> a : 2   
  #=> book : 1
  #=> is : 2  
  #=> pen : 1 
  #=> this : 2
end

__END__
This is a pen.
This is a book.

Enumerator

words = Enumerator.new do |y|
  DATA.each do |line|
    line.scan(/\w+/) do |word|
      y << word.downcase
    end
  end
end

counts = Hash.new(0)
words.each do |word|
  counts[word] += 1
end

counts.keys.sort.each do |k|
  puts "#{k} : #{counts[k]}"
  #=> a : 2
  #=> book : 1
  #=> is : 2
  #=> pen : 1
  #=> this : 2
end

__END__
This is a pen.
This is a book.

速度比較

読み込み対象の文字列を1万行書いて速度を比較したらEnumeratorの方がFiberより速かった。

$ time ruby fiber.rb
a : 10000
is : 10000
pen : 10000
this : 10000
ruby fiber.rb  0.12s user 0.00s system 98% cpu 0.128 total

$ time ruby enum.rb
a : 10000
is : 10000
pen : 10000
this : 10000
ruby enum.rb  0.09s user 0.00s system 98% cpu 0.098 total