Watson1978
1/9/2012 - 5:24 PM

bm_str_scan.rb

# -*- coding: utf-8 -*-
require 'benchmark'

Benchmark.bm do |x|
  freq = Hash.new(0)

  str = "abcd " * 8000 + "あいうえお"

  x.report "case 1" do
    str.downcase.scan(/\w+/){|word| freq[word] += 1}
  end

  x.report "case 2" do
    str.downcase.scan(/\w+/){|word| freq[$&] += 1}
  end

end
$ macruby bm_str_scan.rb
      user     system      total        real
case 1  0.060000   0.000000   0.060000 (  0.051347)
case 2  2.170000   0.010000   2.180000 (  2.166405)

$ ruby19 -v bm_str_scan.rb
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.2.0]
      user     system      total        real
case 1  0.000000   0.000000   0.000000 (  0.009978)
case 2  0.010000   0.000000   0.010000 (  0.011074)

$ ruby -v bm_str_scan.rb 
ruby 1.8.7 (2010-01-10 patchlevel 249) [universal-darwin11.0]
      user     system      total        real
case 1  0.020000   0.000000   0.020000 (  0.023979)
case 2  0.030000   0.000000   0.030000 (  0.026392)