rubyの文字列結合のパフォーマンス比較

動機

ログ出力の文字列整形をしていて、そういえばどの方法が速いのかなぁと。ググるのも面倒なので自分でやってみるかと。

ベンチマーク

#!/usr/bin/ruby

require 'benchmark'

$n = 1000000

def bench(str1,str2,str3,str4)
  Benchmark.bm do |job|
    job.report {
      $n.times do
        message = "[%s][%s][%s] %s\n" % [str1,str2,str3,str4]
      end
    }
    job.report {
      $n.times do
        message = "[#{str1}][#{str2}][#{str3}] #{str4}\n" 
      end
    }
    job.report {
      $n.times do
        message = "[".concat(str1).concat("][").concat(str2).concat("][").concat(str3).concat("] ").concat(str4).concat("\n") 
      end
    }
    job.report {
      $n.times do
        message = "["+ str1 + "][" + str2 + "][" + str3 + "] " + str4 + "\n" 
      end
    }
  end
end

str1 = "20080909101010"
str2 = "12345"
str3 = "INFO"
str4 = "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
bench(str1,str2,str3,str4)

str1 = "0123456789" * 100
str2 = "12345"
str3 = "0123456789" * 100
str4 = "0123456789" * 100
bench(str1,str2,str3,str4)

str1 = "0123456789" * 1000
str2 = "12345"
str3 = "0123456789" * 1000
str4 = "0123456789" * 1000
bench(str1,str2,str3,str4)

想定

一回目のベンチはうちで使ってるなログの出力っぽいやつ(本当は[%s][%5d][%s]..とかにしたいけど条件を統一するため%sで)
二回目、三回目のベンチはまぁなんとなく

結果

一回目
      user     system      total        real
  2.930000   0.000000   2.930000 (  2.929655)
  2.220000   0.000000   2.220000 (  2.274048)
  4.560000   0.000000   4.560000 (  4.857723)
  7.260000   0.000000   7.260000 (  7.399845)
      user     system      total        real
  5.490000   0.000000   5.490000 (  5.547551)
  4.550000   0.360000   4.910000 (  4.980317)
  6.640000   0.000000   6.640000 (  6.632605)
 15.820000   1.130000  16.950000 ( 17.550156)
      user     system      total        real
 32.520000   0.000000  32.520000 ( 32.846656)
 43.260000   8.890000  52.150000 ( 53.031478)
 46.020000  13.910000  59.930000 ( 60.965637)
113.460000   0.010000 113.470000 (114.987965)

二回目
      user     system      total        real
  2.940000   0.000000   2.940000 (  2.935947)
  2.180000   0.000000   2.180000 (  2.224964)
  4.650000   0.000000   4.650000 (  4.649069)
  7.310000   0.000000   7.310000 (  7.344898)
      user     system      total        real
  5.450000   0.000000   5.450000 (  5.895069)
  4.470000   0.400000   4.870000 (  4.947845)
  6.540000   0.000000   6.540000 (  6.582057)
 15.950000   1.040000  16.990000 ( 17.194063)
      user     system      total        real
 30.770000   0.000000  30.770000 ( 31.479092)
 42.610000   8.580000  51.190000 ( 51.877423)
 46.940000  13.230000  60.170000 ( 72.847821)
113.800000   0.010000 113.810000 (118.681130)

所感

うーーーむ
まずは何も考えずに#{}を使っとけってかんじか??