Created
August 14, 2015 12:29
-
-
Save goodniceweb/85665d4fcfc3f1c0a423 to your computer and use it in GitHub Desktop.
Gist shows benchmark code for adding prefix to string in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "benchmark/ips" | |
def use_array_join | |
str = "world" | |
prefix = "Hello, " | |
[prefix, str].join # => "Hello, world" | |
end | |
def use_insert | |
str = "world" | |
str.insert(0, "Hello, ") # => Hello, world | |
end | |
def use_squarebrackets1 | |
str = "world" | |
str[/\A/] = "Hello, " # => "Hello, " | |
str # => "Hello, world" | |
end | |
def use_squarebrackets2 | |
str = "world" | |
str[0,0] = "Hello, " # => "Hello, " | |
str # => "Hello, world" | |
end | |
def use_prepend | |
str = "world" | |
str.prepend("Hello, ") # => "Hello, world" | |
end | |
Benchmark.ips do |x| | |
x.report("Array#join") { use_array_join } | |
x.report("String#insert") { use_insert } | |
x.report('String#[\/A\]') { use_squarebrackets1 } | |
x.report("String#[0,0]") { use_squarebrackets2 } | |
x.report("String#prepend") { use_prepend } | |
x.compare! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What about that?
Also: