Skip to content

Commit

Permalink
Replacing regular expression with string comparison
Browse files Browse the repository at this point in the history
Based on benchmarking, string comparison is faster than regular
express. I also believe that `end_with?(".")` reads better than
mentally parsing a regular expression; It is certainly more "new
developer" friendly.

Here is the benchmark that I ran locally to test performance:

```ruby
require 'benchmark'
n = 30_000_000
Benchmark.bm do |x|
  x.report { n.times { ".".end_with?(".") } }
  x.report { n.times { "." =~ /\.$/ } }
end

```

And here are the results:

```log
    user     system      total        real
4.108148   0.021553   4.129701 (  4.194707)
7.508562   0.018433   7.526995 (  7.585707)
```

And as a bonus, when attempting to bump Rubocop's `TargetRubyVersion`
from `2.3` to `2.4`, the one violation was that we were using `=~`.
Rubocop recommended that we switch to `match?` for regular
expressions.
  • Loading branch information
jeremyf committed Feb 2, 2020
1 parent cb30826 commit 9ce198c
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 4 deletions.
Expand Up @@ -41,7 +41,7 @@ def format_authors(authors_list = [])
text << ", " << author
end
end
text << "." unless text =~ /\.$/
text << "." unless text.end_with?(".")
text
end

Expand Down
Expand Up @@ -35,7 +35,7 @@ def format_authors(authors_list = [])
text << " et al." if authors_list.length > 7
# if for some reason the first author ended with a comma
text.gsub!(',,', ',')
text << "." unless text =~ /\.$/
text << "." unless text.end_with?(".")
whitewash(text)
end
# rubocop:enable Metrics/MethodLength
Expand All @@ -45,7 +45,7 @@ def format_date(pub_date); end
def format_title(title_info)
return "" if title_info.blank?
title_text = chicago_citation_title(title_info)
title_text << '.' unless title_text =~ /\.$/
title_text << '.' unless title_text.end_with?(".")
title_text = whitewash(title_text)
" <i class=\"citation-title\">#{title_text}</i>"
end
Expand Down
Expand Up @@ -27,7 +27,7 @@ def format_authors(authors_list = [])
authors_list = Array.wrap(authors_list)
text = concatenate_authors_from(authors_list)
if text.present?
text << "." unless text =~ /\.$/
text << "." unless text.end_with?(".")
text << " "
end
text
Expand Down

0 comments on commit 9ce198c

Please sign in to comment.