Permalink
Browse files

Replace regexp matching with a simple string manipulation.

Using regexp looks like overkill here and is also 2x slower.

             user     system      total        real
string   0.020000   0.000000   0.020000 (  0.016256)
regexp   0.030000   0.000000   0.030000 (  0.035360)

require "benchmark"

names = ("a".."z").map { |c| c + "a" * rand(5..10) + "=" * rand(0..1) }.map(&:to_sym)
puts names

n = 1000
Benchmark.bmbm do |x|
  x.report "string" do
    n.times do
      names.each do |name|
        string_name = name.to_s
        string_name.chomp!('=')
        string_name
      end
    end
  end

  x.report "regexp" do
    n.times do
      names.each do |name|
        name.to_s =~ /(.*)=$/
        $1
      end
    end
  end
end
  • Loading branch information...
1 parent 2e13850 commit bb1813cab859a404ffbb0bc8077407632b92a2f1 @semaperepelitsa semaperepelitsa committed Jan 21, 2012
Showing with 3 additions and 2 deletions.
  1. +3 −2 activesupport/lib/active_support/ordered_options.rb
@@ -30,8 +30,9 @@ def [](key)
end
def method_missing(name, *args)
- if name.to_s =~ /(.*)=$/
- self[$1] = args.first
+ name_string = name.to_s
+ if name_string.chomp!('=')
+ self[name_string] = args.first
else
self[name]
end

0 comments on commit bb1813c

Please sign in to comment.