Skip to content

Instantly share code, notes, and snippets.

@yury
Last active December 15, 2015 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yury/5248925 to your computer and use it in GitHub Desktop.
Save yury/5248925 to your computer and use it in GitHub Desktop.
require 'benchmark'
def byte_can_encode(str)
str.each_char do |c|
# simple range checks for most common characters (' '..'_') or ('a'..'~')
b = c.getbyte(0)
unless b >= 0x20 && b <= 0x5F || b >= 0x61 && b <= 0x7E
return false
end
end
true
end
def string_can_encode(str)
str.each_char do |c|
# simple range checks for most common characters (' '..'_') or ('a'..'~')
unless c >= ' ' && c <= '_' || c >= 'a' && c <= '~'
return false
end
end
true
end
Benchmark.bm do |r|
N = 100_000
POSITIVE = (' '..'_').to_a.join('')
NEGATIVE = POSITIVE + 'привет'
r.report("string positive") do
N.times { string_can_encode(POSITIVE)}
end
r.report("byte positive") do
N.times { byte_can_encode(POSITIVE) }
end
r.report("string negative") do
N.times { string_can_encode(NEGATIVE)}
end
r.report("byte negative") do
N.times { byte_can_encode(NEGATIVE) }
end
end
# user system total real
# string positive 3.120000 0.000000 3.120000 ( 3.112871)
# byte positive 1.150000 0.000000 1.150000 ( 1.156764)
# string negative 3.210000 0.000000 3.210000 ( 3.202055)
# byte negative 1.190000 0.000000 1.190000 ( 1.196076)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment