Watson1978
7/2/2011 - 5:34 PM

MacRuby : benchmark that read a file

MacRuby : benchmark that read a file

framework 'Foundation'
require 'benchmark'

File.open("/tmp/bm_read.txt", "w") {|f|
  str = "x" * 10_000_000
  f.write str
}

Benchmark.bm(20) do |x|
  error = Pointer.new(:object)

  x.report "NSString" do
    10.times do
      str = NSString.stringWithContentsOfFile("/tmp/bm_read.txt",
                                              encoding:NSUTF8StringEncoding,
                                              error:error)
    end
  end

  x.report "NSMutableString" do
    10.times do
      str = NSMutableString.stringWithContentsOfFile("/tmp/bm_read.txt",
                                                     encoding:NSUTF8StringEncoding,
                                                     error:error)
    end
  end

  x.report "NSData" do
    10.times do
      data = NSData.dataWithContentsOfFile("/tmp/bm_read.txt")
      str  = String.new(data)
    end
  end

  x.report "IO.read" do
    10.times do
      io = File.open("/tmp/bm_read.txt")
      str = io.read
      io.close
    end
  end
end
                          user     system      total        real
NSString              0.120000   0.060000   0.180000 (  0.169725)
NSMutableString       0.180000   0.110000   0.290000 (  0.192904)
NSData                0.290000   0.150000   0.440000 (  0.238627)
IO.read               0.440000   0.180000   0.620000 (  0.323505)