-
-
Save mjc-gh/0339162c97ffd4257d674c0bfb71e37f to your computer and use it in GitHub Desktop.
How fast is `reverse!` technique.
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
# conversation: https://github.com/rack/rack/commit/734a00c5f4bb46e9a5e6e2677d89a2f285dcc185 | |
# | |
# user system total real | |
# reverse: 0.030000 0.010000 0.040000 ( 0.046804) | |
# join: 0.090000 0.000000 0.090000 ( 0.092356) | |
# regexp: 0.080000 0.000000 0.080000 ( 0.087152) | |
# slice 0.010000 0.000000 0.010000 ( 0.004146) | |
require 'benchmark' | |
def join(session_data) | |
*data, digest = session_data.split('--') | |
session_data = data.join('--') | |
[session_data, digest] | |
end | |
def reverse(session_data) | |
digest, session_data = session_data.reverse.split('--', 2) | |
digest.reverse! if digest | |
session_data.reverse! if session_data | |
[session_data, digest] | |
end | |
REGEXP = /\A(.*)--(.*)\z/m | |
def regexp(session_data) | |
session_data, digest = REGEXP.match(session_data).captures | |
[session_data, digest] | |
end | |
SHA1_DIGEST_SIZE = 40 | |
def slice(session_data) | |
digest = session_data.slice!(-SHA1_DIGEST_SIZE..-1) | |
session_data.slice!(-2..-1) # remove the double dash | |
[session_data, digest] | |
end | |
n = 1000 | |
data = (1..100).to_a.map!{|i| i.to_s * 100}.join('--') | |
Benchmark.bm(8) do |x| | |
x.report('reverse:') { n.times { reverse(data) } } | |
x.report('join:') { n.times { join(data) } } | |
x.report('regexp:') { n.times { regexp(data) } } | |
x.report('slice') { n.times { slice(data) } } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment