-
-
Save uu59/1566407 to your computer and use it in GitHub Desktop.
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
# http://patshaughnessy.net/2012/1/4/never-create-ruby-strings-longer-than-23-characters | |
require 'benchmark' | |
ITERATIONS = 2000000 # original script was 1000000 | |
def run(str, bench, op=nil) | |
p = case op | |
when :<< | |
lambda { new_string = str << "x" } # String#<< は破壊的なので毎回strも変わる | |
else | |
lambda { new_string = str + "x" } | |
end | |
bench.report("#{str.length + 1} chars by #{op}") do | |
ITERATIONS.times do | |
p.call | |
end | |
end | |
end | |
Benchmark.bm do |bench| | |
[:<<, :+].each do |op| | |
run("12345678901234567890", bench, op) | |
run("123456789012345678901", bench, op) | |
run("1234567890123456789012", bench, op) | |
run("12345678901234567890123", bench, op) | |
run("123456789012345678901234", bench, op) | |
run("1234567890123456789012345", bench, op) | |
run("12345678901234567890123456", bench, op) | |
end | |
end | |
=begin | |
$ ruby -v | |
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-linux] | |
user system total real | |
21 chars by << 0.570000 0.000000 0.570000 ( 0.569075) | |
22 chars by << 0.560000 0.000000 0.560000 ( 0.560594) | |
23 chars by << 0.570000 0.000000 0.570000 ( 0.562083) | |
24 chars by << 0.580000 0.000000 0.580000 ( 0.583945) | |
25 chars by << 0.590000 0.000000 0.590000 ( 0.591878) | |
26 chars by << 0.560000 0.000000 0.560000 ( 0.563446) | |
27 chars by << 0.560000 0.000000 0.560000 ( 0.558477) | |
21 chars by + 0.630000 0.000000 0.630000 ( 0.627031) | |
22 chars by + 0.700000 0.000000 0.700000 ( 0.703161) | |
23 chars by + 0.700000 0.000000 0.700000 ( 0.694024) | |
24 chars by + 0.780000 0.000000 0.780000 ( 0.789131) | |
25 chars by + 0.790000 0.000000 0.790000 ( 0.789473) | |
26 chars by + 0.790000 0.000000 0.790000 ( 0.796314) | |
27 chars by + 0.800000 0.000000 0.800000 ( 0.797088) | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment