-
Notifications
You must be signed in to change notification settings - Fork 377
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
String#=~ faster than String#match #59
String#=~ faster than String#match #59
Conversation
If you're only looking for presence of a match and don't need the matchdata, use String#=~ schneems/rails@1bf50ba#commitcomment-12572839
In `apply_inflections` a string is down cased and some whitespace stripped in the front (which allocate strings). This would normally be fine, however `uncountables` is a fairly small array (10 elements out of the box) and this method gets called a TON. Instead we can keep an array of valid regexes for each uncountable so we don't have to allocate new strings. This change buys us 325,106 bytes of memory and 3,251 fewer objects per request.
Regexp#=== is a tiny bit faster on my machine, worth including: require 'benchmark/ips'
def fastest
/boo/ === 'foo'.freeze
end
def fast
'foo'.freeze =~ /boo/
end
def slow
'foo'.freeze.match(/boo/)
end
Benchmark.ips do |bm|
bm.report("Regexp#===") { fastest }
bm.report("String#=~") { fast }
bm.report("String#match") { slow }
bm.compare!
end
|
Yep
Seems good. How should I report this? I would like to have all 3 examples in the code and reported. |
Edited my comment as String#=== was wrong, I meant Regexp#=== |
How about list all possibilities ( require "benchmark/ips"
def fastest
"foo".freeze === /boo/
end
def faster
"foo".freeze =~ /boo/
end
def fast
/boo/ === "foo".freeze
end
def slow
"foo".freeze.match(/boo/)
end
Benchmark.ips do |x|
x.report("String#===") { fastest }
x.report("Regexp#===") { faster }
x.report("String#=~") { fast }
x.report("String#match") { slow }
x.compare!
end
❓ |
String#=== doesn't work, it's not the correct result. |
Yup. The #59 (comment) is wrong. Let's keep this simple since the regexp need to flip the string to be compared to the end. Which is counterintuitive |
String#=~ faster than String#match
It's a pretty big speed boost, we would have to rename it to |
If you're only looking for presence of a match and don't need the matchdata, use String#=~
schneems/rails@1bf50ba#commitcomment-12572839