Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace regexp matching with a simple string manipulation. #4572

Merged
merged 1 commit into from Jan 21, 2012

Conversation

semaperepelitsa
Copy link
Contributor

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

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
josevalim added a commit that referenced this pull request Jan 21, 2012
Replace regexp matching with a simple string manipulation.
@josevalim josevalim merged commit c05f3b0 into rails:master Jan 21, 2012
@jonleighton
Copy link
Member

@semaperepelitsa FWIW I am not very convinced by this benchmark. N is too small to draw any meaningful conclusions. But I don't have a problem with this patch being merged, just a heads up that you should benchmark over more iterations in the future :)

@semaperepelitsa
Copy link
Contributor Author

I've benchmarked for 10_000 and 100_000 as well, the numbers have grown linearly 10x and 100x respectively. Picked up the most realistic yet big enough number :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants