Skip to content

Instantly share code, notes, and snippets.

@jgarber
Created January 24, 2012 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgarber/1670877 to your computer and use it in GitHub Desktop.
Save jgarber/1670877 to your computer and use it in GitHub Desktop.
What's the fastest way to convert from a subclass of String to a String?
#!/usr/bin/env ruby
require 'benchmark'
TIMES_TO_REPEAT = 10_000_000
class SpecialString < String; end
Benchmark.bmbm do|b|
b.report("''.to_s") do
str = ''
TIMES_TO_REPEAT.times { str.to_s }
end
b.report('"".to_s') do
str = ""
TIMES_TO_REPEAT.times { str.to_s }
end
b.report("String(str)") do
str = SpecialString.new("")
TIMES_TO_REPEAT.times { String(str) }
end
b.report("str.to_s") do
str = SpecialString.new("")
TIMES_TO_REPEAT.times { str.to_s }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment