On Thu, Mar 20, 2008 at 01:44:11AM +0900, Gerardo Santana G?mez Garrido wrote:
> Replace output.write("hola mundo\n") with output.puts("hola mundo")
> and you'll get something similar.

Not much difference, and the StringIO solution uses more memory.  Not
surprising, since both File#puts and StringIO#puts are implemented by
rb_io_puts.

The difference may be more dramatic on your platform, depending on the
implementation of your C library's stdio functions.

[pbrannan@zaphod tmp]$ ruby -v
ruby 1.8.6 (2007-09-24 patchlevel 111) [i686-linux]
[pbrannan@zaphod tmp]$ ruby test.rb
Rehearsal --------------------------------------------------
IO#puts         10.320000   0.010000  10.330000 ( 10.412573)
IO#write         5.110000   0.020000   5.130000 (  5.171733)
StringIO#puts    9.740000   0.060000   9.800000 (  9.847963)
StringIO#write   4.430000   0.040000   4.470000 (  4.504434)
---------------------------------------- total: 29.730000sec

                     user     system      total        real
IO#puts         10.220000   0.010000  10.230000 ( 10.258458)
IO#write         5.090000   0.020000   5.110000 (  5.164432)
StringIO#puts   10.150000   0.160000  10.310000 ( 10.438876)
StringIO#write   4.630000   0.090000   4.720000 (  4.769139)
[pbrannan@zaphod tmp]$ cat test.rb
require 'stringio'
require 'benchmark'

Benchmark.bmbm(15) do |x|
  devnull = File.open('/dev/null', 'w')
  n = 2_000_000

  x.report("IO#puts") {
    n.times do
      devnull.puts "hola"
    end
  }

  x.report("IO#write") {
    n.times do
      devnull.write "hola\n"
    end
  }

  x.report("StringIO#puts") {
    s = StringIO.new
    n.times do
      s.puts "hola"
    end
    s.rewind
    devnull.print s.read
  }

  x.report("StringIO#write") {
    s = StringIO.new
    n.times do
      s.write "hola\n"
    end
    s.rewind
    devnull.print s.read
  }
end