Ruby casecmp vs downcase
pro-tip that I learned today:
when comparing case-insensitive strings, this can be 1.2x to 2x faster:
str = "TEST"
str.casecmp?("test")than this:
str = "TEST"
str.downcase == "test"Caveat: non-ASCII/Unicode strings can behave differently with downcase vs casecmp
9
Upvotes
4
u/h0rst_ 23d ago
https://docs.rubocop.org/rubocop-performance/latest/cops_performance.html#performancecasecmp
You can automate the checks. I always had this one disabled, because I found the
str.casecmp(arg) == 0too ugly for the small performance gains (I mean, how often is this code your bottleneck), but the predicate method looks acceptable.4
u/sshaw_ 23d ago
Also note
#casecmp?vs theInteger-returning#casecmp: https://github.com/fastruby/fast-ruby/tree/c54a4742ba1b7dfb570e4483ac8ccc986d804c23#stringcasecmp-vs--stringcasecmp-vs-stringdowncase---codeAnd others, noted by fastruby.