Skip to content

Instantly share code, notes, and snippets.

@goodniceweb
Created August 14, 2015 12:29
Show Gist options
  • Save goodniceweb/85665d4fcfc3f1c0a423 to your computer and use it in GitHub Desktop.
Save goodniceweb/85665d4fcfc3f1c0a423 to your computer and use it in GitHub Desktop.
Gist shows benchmark code for adding prefix to string in Ruby
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
@zankevich
Copy link

What about that?

def use_arrows
  str = "world"
  "Hello, " << str # => "Hello, world"
end
Comparison:
           String#<<:  2836395.5 i/s
       String#insert:  2599252.8 i/s - 1.09x slower
      String#prepend:  2504770.5 i/s - 1.13x slower
        String#[0,0]:  2407843.9 i/s - 1.18x slower
          Array#join:  1244613.4 i/s - 2.28x slower
       String#[\/A\]:   710030.8 i/s - 3.99x slower

Also:

def use_arr_index
  str = "world"
  str[0] = "Hello, " # => "Hello, world"
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment