Watson1978
10/29/2011 - 12:15 AM

bm_str_length.rb

require 'benchmark'

Benchmark.bm(15) do |x|
  str = "abcdef" * 10000000
  x.report "#size" do
    str.size
  end

  x.report "#length (1)" do
    # first time
    str.length
  end

  x.report "#length (2)" do
    # second time
    str.length
  end

  str2 = str.dup
  x.report "#length (3)" do
    str2.length
  end
end
require 'benchmark'

Benchmark.bm(15) do |x|
  str = "abcdef" * 10000000
  x.report "#size" do
    1000.times do
      str.size
    end
  end

  x.report "#length (1)" do
    # first time
    1000.times do
      str.length
    end
  end

  x.report "#length (2)" do
    # second time
    1000.times do
      str.length
    end
  end

  str2 = str.dup
  x.report "#length (3)" do
    1000.times do
      str2.length
    end
  end
end
$ ruby -v --1.9 bm_str_length.rb
jruby 1.6.5 (ruby-1.9.2-p136) (2011-10-25 9dcd388) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_26) [darwin-x86_64-java]
                     user     system      total        real
#size            0.001000   0.000000   0.001000 (  0.001000)
#length (1)      0.000000   0.000000   0.000000 (  0.000000)
#length (2)      0.000000   0.000000   0.000000 (  0.000000)
#length (3)      0.000000   0.000000   0.000000 (  0.001000)

$ ruby19 -v bm_str_length.rb 
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.2.0]
                     user     system      total        real
#size            0.000000   0.000000   0.000000 (  0.000012)
#length (1)      0.000000   0.000000   0.000000 (  0.000005)
#length (2)      0.000000   0.000000   0.000000 (  0.000005)
#length (3)      0.000000   0.000000   0.000000 (  0.000005)


$ ruby -v --1.9 bm_str_length2.rb
jruby 1.6.5 (ruby-1.9.2-p136) (2011-10-25 9dcd388) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_26) [darwin-x86_64-java]
                     user     system      total        real
#size            0.011000   0.000000   0.011000 (  0.011000)
#length (1)      0.011000   0.000000   0.011000 (  0.011000)
#length (2)      0.009000   0.000000   0.009000 (  0.009000)
#length (3)      0.009000   0.000000   0.009000 (  0.009000)

$ ruby19 -v bm_str_length2.rb    
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.2.0]
                     user     system      total        real
#size            0.000000   0.000000   0.000000 (  0.000132)
#length (1)      0.000000   0.000000   0.000000 (  0.000100)
#length (2)      0.000000   0.000000   0.000000 (  0.000108)
#length (3)      0.000000   0.000000   0.000000 (  0.000098)