ziq
ziq

Reputation: 1018

Which is the faster way when checking if two strings or RegExp match exactly?

Which is the faster way (in character level) when checking if two strings or RegExp match exactly? If the string is extremely long or have to check many times?

  1. str == str_or_regexp || str =~ str_or_regexp

  2. str[str_or_regexp] == str

Or there is better way?

We don't know str_or_regexp is a string or a regular expression until runtime.

Upvotes: 0

Views: 132

Answers (2)

Brandan
Brandan

Reputation: 14983

When all else fails, run some tests:

str = 'string'
s = 'string'
r = /string/

methods = {
  :equals_or_matches => lambda { |t| str == t || str =~ t },
  :square_brackets => lambda { |t| str[t] == str }
}

methods.each_pair do |name, method|
  puts name

  [s, r].each do |t|
    puts t.class

    5.times do
      start = Time.now
      1000000.times do
        method.call(t)
      end
      puts Time.now - start
    end
  end

  puts
end

I got these results:

equals_or_matches
String
0.942799
0.942405
0.944376
0.946296
0.93843
Regexp
1.916263
1.915058
1.913306
1.934423
1.932633

square_brackets
String
1.15087
1.157245
1.157863
1.174356
1.188758
Regexp
2.09721
2.103493
2.028035
2.025194
2.037734

That indicates that your first method is a little bit faster than your second.

However, if the strings are not equal and the || doesn't "short circuit", you'll get a TypeError. You can't pass a string to =~. So you should probably replaced that with str.match(t), which gave me these results:

equals_or_matches
String
0.936063
0.94154
0.938561
0.934187
0.935868
Regexp
2.755815
2.75011
2.758374
2.761684
2.76826

square_brackets
String
1.198433
1.160929
1.354407
1.410265
1.274158
Regexp
2.013017
2.275579
2.297108
2.165399
2.125889

In that case, your first method fared much worse for regexps, but the second was about the same.

Like I said, just run some tests on real data and see what happens.

Upvotes: 3

ScottJShea
ScottJShea

Reputation: 7111

I prefer string.match(pattern) myself and it seems to be the suggested method. Here are the core docs for it.

Upvotes: 0

Related Questions