Created
March 5, 2009 07:39
-
-
Save solebared/74249 to your computer and use it in GitHub Desktop.
Benchmarking ways to insert a separator at every 80 characters of a string
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
# Benchmarking ways to insert a separator at every 80 characters of a string | |
# | |
# Original question asked here: | |
# http://www.nabble.com/Cut-a-string-each-80-character-td22343923.html | |
# | |
# This version based on improvements suggested by Robert Klemme | |
require 'benchmark' | |
S = ('0123456789' * (80 * 100)).freeze | |
R = '<br/>'.freeze | |
GS = "\\&#{R}".freeze | |
SANE = '<br/>0123456789'.freeze | |
DELTA = 80 + R.length | |
REP = 500 | |
def with_scan s | |
s = s.scan(/.{80}/).join(R) | |
raise 'with_scan failed' unless s[-85..-71] == SANE | |
end | |
def with_gsub s | |
s = s.gsub!(/.{80}/, GS).chomp!(R) | |
raise 'with_gsub failed' unless s[-85..-71] == SANE | |
end | |
def with_insert s | |
i = 80 | |
while i < s.length | |
s.insert i, R | |
i += DELTA | |
end | |
raise 'with_insert failed' unless s[-85..-71] == SANE | |
end | |
Benchmark.bmbm do |bm| | |
bm.report('with_scan ') { REP.times { with_scan S.dup }} | |
bm.report('with_gsub ') { REP.times { with_gsub S.dup }} | |
bm.report('with_insert') { REP.times { with_insert S.dup }} | |
end | |
=begin | |
ruby 1.8.7 (2008-08-11 patchlevel 72) [i686-darwin8] | |
Rehearsal ----------------------------------------------- | |
with_scan 4.790000 0.240000 5.030000 ( 5.147447) | |
with_gsub 4.860000 0.270000 5.130000 ( 5.279766) | |
with_insert 10.350000 0.170000 10.520000 ( 10.688951) | |
------------------------------------- total: 20.680000sec | |
user system total real | |
with_scan 4.770000 0.230000 5.000000 ( 5.086956) | |
with_gsub 4.790000 0.250000 5.040000 ( 5.138912) | |
with_insert 10.360000 0.170000 10.530000 ( 10.780026) | |
ruby 1.8.7 (2008-08-11 patchlevel 72) [i686-darwin8] | |
Rehearsal ----------------------------------------------- | |
with_scan 4.800000 0.250000 5.050000 ( 5.295321) | |
with_gsub 4.870000 0.280000 5.150000 ( 5.271513) | |
with_insert 10.370000 0.180000 10.550000 ( 10.851188) | |
------------------------------------- total: 20.750000sec | |
user system total real | |
with_scan 4.780000 0.230000 5.010000 ( 5.135472) | |
with_gsub 4.800000 0.260000 5.060000 ( 5.213397) | |
with_insert 10.380000 0.190000 10.570000 ( 10.953337) | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment