Last active
June 4, 2017 06:41
-
-
Save tonytonyjan/8623c212683ffe6a1943fe16e7aed8b3 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.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