Last active
June 21, 2016 00:12
-
-
Save phoffer/5f09da6b57d23af842ed3cf2fda423f5 to your computer and use it in GitHub Desktop.
timing two different crystal implementations of String#blank?
This file contains hidden or 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
# crystal version: 0.17.4 | |
struct Char | |
def blank? | |
case ord | |
when 9, 0xa, 0xb, 0xc, 0xd, 0x20, 0x85, 0xa0, 0x1680, 0x180e, | |
0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, | |
0x2007, 0x2008, 0x2009, 0x200a, 0x2028, 0x2029, 0x202f, | |
0x205f, 0x3000 then true | |
else | |
false | |
end | |
end | |
end | |
class String | |
BLANK_RE = /\A[[:space:]]*\z/ | |
# A string is blank if it's empty or contains whitespaces only: | |
# | |
# ''.blank? # => true | |
# ' '.blank? # => true | |
# "\t\n\r".blank? # => true | |
# ' blah '.blank? # => false | |
# | |
# Unicode whitespace is supported: | |
# | |
# "\u00a0".blank? # => true | |
# | |
# @return [true, false] | |
def blank_old? | |
# The regexp that matches blank strings is expensive. For the case of empty | |
# strings we can speed up this method (~3.5x) with an empty? call. The | |
# penalty for the rest of strings is marginal. | |
empty? || BLANK_RE === self | |
end | |
def blank? | |
empty? || each_char.all? &.blank? | |
end | |
end | |
puts "timing blank methods" | |
count = 50_000_000 | |
strings = ["#{0xa0.chr}", "\t\n", " ", "a", "a ", ""] | |
strings.each do |str| | |
t1 = Time.now | |
count.times do |i| | |
" ".blank_old? | |
end | |
t2 = Time.now | |
count.times do |i| | |
" ".blank? | |
end | |
t3 = Time.now | |
puts "---- #{str.inspect} ----" | |
puts "time old: #{t2 - t1}" | |
puts "time new: #{t3 - t2}" | |
end |
This file contains hidden or 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
# crystal version: 0.17.4 | |
---- " " ---- | |
time old: 00:00:12.0384530 | |
time new: 00:00:12.4862200 | |
---- "\t\n" ---- | |
time old: 00:00:12.1807940 | |
time new: 00:00:12.6070700 | |
---- " " ---- | |
time old: 00:00:12.2025870 | |
time new: 00:00:12.5745790 | |
---- "a" ---- | |
time old: 00:00:11.9885690 | |
time new: 00:00:12.7635750 | |
---- "a " ---- | |
time old: 00:00:12.1138550 | |
time new: 00:00:12.7864930 | |
---- "" ---- | |
time old: 00:00:11.9982170 | |
time new: 00:00:12.5567060 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment