Created
June 28, 2020 19:26
-
-
Save jgaskins/f18d0001969725340c023056a429bde9 to your computer and use it in GitHub Desktop.
Compare parsing an int as intermediate strings vs using a byte parser directly on the IO
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
require "benchmark" | |
int = 0 | |
[1, 12, 1234, 12345678, 1234567812345678].each do |number| | |
puts "Parsing #{number}..." | |
io = IO::Memory.new | |
io << ":#{number}\r\n" # Redis integer format | |
io.rewind | |
Benchmark.ips do |x| | |
x.report "to_i" do | |
case byte = io.rewind.read_byte | |
when ':' | |
int = io.read_line.to_i64 | |
end | |
end | |
x.report "byte" do | |
int = 0i64 | |
case byte = io.rewind.read_byte | |
when ':' | |
loop do | |
case (next_byte = io.read_byte) | |
when '\r', '\n', nil | |
break | |
when '0'.ord..'9'.ord | |
int *= 10 | |
int += next_byte - '0'.ord | |
else | |
break | |
end | |
end | |
end | |
end | |
end | |
puts | |
end | |
pp int |
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
Parsing 1... | |
to_i 29.71M ( 33.65ns) (± 0.51%) 16.0B/op 6.14× slower | |
byte 182.42M ( 5.48ns) (± 1.06%) 0.0B/op fastest | |
Parsing 12... | |
to_i 28.14M ( 35.54ns) (± 1.11%) 16.0B/op 4.56× slower | |
byte 128.41M ( 7.79ns) (± 1.34%) 0.0B/op fastest | |
Parsing 1234... | |
to_i 23.85M ( 41.93ns) (± 4.85%) 32.0B/op 3.38× slower | |
byte 80.68M ( 12.39ns) (± 1.12%) 0.0B/op fastest | |
Parsing 12345678... | |
to_i 21.22M ( 47.12ns) (± 0.73%) 32.0B/op 2.14× slower | |
byte 45.47M ( 21.99ns) (± 3.65%) 0.0B/op fastest | |
Parsing 1234567812345678... | |
to_i 17.98M ( 55.62ns) (± 0.44%) 32.0B/op 1.38× slower | |
byte 24.80M ( 40.32ns) (± 0.45%) 0.0B/op fastest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment