Skip to content

Instantly share code, notes, and snippets.

@ms-ati
Last active August 1, 2017 15:27
Show Gist options
  • Save ms-ati/e61de6734fe12df823b41cb67cf344b3 to your computer and use it in GitHub Desktop.
Save ms-ati/e61de6734fe12df823b41cb67cf344b3 to your computer and use it in GitHub Desktop.
What's the fast way to choose "a" vs "an" English article in Ruby?
# frozen_string_literal: true
#
# What's the fast way to choose "a" vs "an" English article in Ruby?
#
# Based on / inspired by: https://github.com/JuanitoFatas/fast-ruby/blob/master/code/string/start-string-checking-match-vs-start_with.rb
# See more at https://github.com/JuanitoFatas/fast-ruby
#
require 'benchmark/ips'
SLUG = 'Xerox'
PREFIX_REGEX = /^[aefhilmnorsx]/i
PREFIX_CHARS = %w(a e f h i l m n o r s x).flat_map { |l| [l, l.upcase] }.freeze
def slow
SLUG =~ PREFIX_REGEX ? "an" : "a"
end
def fast
SLUG.start_with?(*PREFIX_CHARS) ? "an" : "a"
end
Benchmark.ips do |x|
x.report('String#=~') { slow }
x.report('String#start_with?') { fast }
x.compare!
end
$ ruby -v
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
$ ruby ruby_fast_choose_article.rb
Warming up --------------------------------------
           String#=~    98.496k i/100ms
  String#start_with?   148.433k i/100ms
Calculating -------------------------------------
           String#=~      1.292M (± 2.7%) i/s -      6.501M in   5.034701s
  String#start_with?      2.267M (± 2.4%) i/s -     11.429M in   5.044754s

Comparison:
  String#start_with?:  2266957.7 i/s
           String#=~:  1292136.3 i/s - 1.75x  slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment