Skip to content

Instantly share code, notes, and snippets.

@tonytonyjan
Last active June 4, 2017 06:41
Show Gist options
  • Save tonytonyjan/8623c212683ffe6a1943fe16e7aed8b3 to your computer and use it in GitHub Desktop.
Save tonytonyjan/8623c212683ffe6a1943fe16e7aed8b3 to your computer and use it in GitHub Desktop.
How fast is `reverse!` technique.
# conversation: https://github.com/rack/rack/commit/734a00c5f4bb46e9a5e6e2677d89a2f285dcc185
#
# user system total real
# reverse: 0.010000 0.010000 0.020000 ( 0.024657)
# join: 0.050000 0.010000 0.060000 ( 0.056571)
# regexp: 0.050000 0.000000 0.050000 ( 0.048339)
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
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) } }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment