String interpolation is faster than printf in Ruby

Just wanted to make a note, string interpolation is faster than printf in Ruby. Example:

$ irb
>> require 'benchmark'
=> true
>> Benchmark.measure { 100000.times {
  "%s" % ["hello world"] } }.total
=> 0.21
>> Benchmark.measure { 100000.times {
  "#{'hello world'}"} }.total
=> 0.04
Share:
  • del.icio.us
  • Reddit
  • Technorati
  • Twitter
  • Facebook
  • Google Bookmarks
  • HackerNews
  • PDF
  • RSS
This entry was posted in ruby. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.
  • John

    on my machine I see that a good portion of that difference is due to putting the string in an array

    1. Baseline:
    Benchmark.measure { 100000.times {“hello world”}}.total
    anywhere from .016 to .032
    2. printf style
    Benchmark.measure {100000.times {“%s” % ["hello world"] }}.total
    consistent at 0.25
    3. interpolation
    Benchmark.measure {100000.times {“#{‘hello world’}”}}.total
    .031

    So at this point the difference between #2 and #3 is 0.219, but if you take out the [] ie
    #4 Benchmark.measure {100000.times {“%s” % “hello world”}}.total
    the number is closer to 0.19 and the difference between #4 and #3 is 0.159

    meaning that about 24% of the difference you were seeing was due to the []. (which doesn’t invalidate your observation at all, interpolation is still way faster than the printf style)