1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

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
This commit is contained in:
Semyon Perepelitsa 2012-01-21 18:15:08 +08:00
parent 2e13850e4c
commit bb1813cab8

View file

@ -30,8 +30,9 @@ module ActiveSupport #:nodoc:
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