Created
February 29, 2016 11:14
-
-
Save angelikatyborska/1e079cfdf2fbbf7a4787 to your computer and use it in GitHub Desktop.
Checking if a string includes only allowed characters - a comparision of using chars.all? vs. regular expressions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
module CharsAllVsRegexp | |
VALID_CHARS = %w(A C G T) | |
REGEXP = Regexp.new("\\A(#{ VALID_CHARS.join('|') })*\\z") | |
ARRAY_LENGTH = 10000 | |
STRING_LENGTH = 5000 | |
STRINGS_GENERATOOR = ->(chars) do | |
ARRAY_LENGTH.times.with_object([]) do |n, strings| | |
strings << STRING_LENGTH.times.with_object('') { |n, string| string << chars.sample } | |
end | |
end | |
def self.validate_via_regexp(string) | |
string =~ REGEXP | |
end | |
def self.validate_via_chars_all(string) | |
string.chars.all? { |char| VALID_CHARS.include?(char) } | |
end | |
def self.run | |
puts 'Generating strings...' | |
random_strings = STRINGS_GENERATOOR.call(('A'..'Z').to_a) | |
valid_strings = STRINGS_GENERATOOR.call(VALID_CHARS) | |
puts 'Running benchmark...' | |
puts "Validating #{ ARRAY_LENGTH } random strings, each #{ STRING_LENGTH } characters long:" | |
Benchmark.bm(15) do |x| | |
x.report('regexp:') { random_strings.each { |string| validate_via_regexp(string)} } | |
x.report('chars.all?:') { random_strings.each { |string| validate_via_chars_all(string)} } | |
end | |
puts "Validating #{ ARRAY_LENGTH } valid strings, each #{ STRING_LENGTH } characters long:" | |
Benchmark.bm(15) do |x| | |
x.report('regexp:') { valid_strings.each { |string| validate_via_regexp(string)} } | |
x.report('chars.all?:') { valid_strings.each { |string| validate_via_chars_all(string)} } | |
end | |
end | |
end | |
CharsAllVsRegexp.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment