Skip to content

Instantly share code, notes, and snippets.

@rob-murray
Created December 24, 2015 10:10
Show Gist options
  • Save rob-murray/83216faa9c4a33d21431 to your computer and use it in GitHub Desktop.
Save rob-murray/83216faa9c4a33d21431 to your computer and use it in GitHub Desktop.
Ruby string formatting performance
require "benchmark/ips"
def with_interpolation(a = "a", b = "b")
"#{a}--#{b}"
end
def with_cryptic_percentage(a = "a", b = "b")
"%s--%s" % [a,b]
end
def with_kernel_format(a = "a", b = "b")
format("%s--%s", a,b)
end
Benchmark.ips do |x|
x.report("with_interpolation") { with_interpolation }
x.report("with_cryptic_percentage") { with_cryptic_percentage }
x.report("with_kernel_format") { with_kernel_format }
x.compare!
end
__END__
Calculating -------------------------------------
with_interpolation 62.236k i/100ms
with_cryptic_percentage
41.634k i/100ms
with_kernel_format 40.623k i/100ms
-------------------------------------------------
with_interpolation 1.478M (± 8.9%) i/s - 7.344M
with_cryptic_percentage
721.723k (± 7.9%) i/s - 3.622M
with_kernel_format 794.553k (± 8.0%) i/s - 3.981M
Comparison:
with_interpolation: 1478331.6 i/s
with_kernel_format: 794552.8 i/s - 1.86x slower
with_cryptic_percentage: 721723.3 i/s - 2.05x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment