Last active
October 2, 2019 13:58
-
-
Save cjjuice/273ac487474203ae38b8e047a18956c0 to your computer and use it in GitHub Desktop.
String reverse benchmarks
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
[179] pry(main)> n = 1000000 | |
=> 1000000 | |
[180] pry(main)> Benchmark.bm(7) do |x| | |
[180] pry(main)* x.report('1:') { ->(str) { n.times { chars = str.chars; (1..chars.length).to_a.tap { |a| chars.each_with_index { |c, i| a[-i-1] = c } }.join } }.call('r4v3n') } | |
[180] pry(main)* x.report('2:') { ->(str) { n.times { [].tap { |a| chars = str.chars; str.size.times { a << chars.pop } }.join } }.call('r4v3n') } | |
[180] pry(main)* x.report('3:') { ->(str) { n.times { str.size/2.times { |i| str[i], str[-i-1] = str[-i-1], str[i] }; str } }.call('r4v3n') } | |
[180] pry(main)* x.report('4:') { ->(str) { n.times { str.reverse } }.call('r4v3n') } | |
[180] pry(main)* end | |
user system total real | |
1: 2.626973 0.019897 2.646870 ( 2.657133) | |
2: 1.911454 0.017483 1.928937 ( 1.936380) | |
3: 1.044563 0.006635 1.051198 ( 1.055289) | |
4: 0.094309 0.000483 0.094792 ( 0.095374) | |
=> [#<Benchmark::Tms:0x00007fdea3db3218 @cstime=0.0, @cutime=0.0, @label="1:", @real=2.657132999971509, @stime=0.01989699999999983, @total=2.6468699999999994, @utime=2.6269729999999996>, | |
#<Benchmark::Tms:0x00007fdebaacb7c8 @cstime=0.0, @cutime=0.0, @label="2:", @real=1.9363799998536706, @stime=0.017482999999999915, @total=1.9289370000000026, @utime=1.9114540000000027>, | |
#<Benchmark::Tms:0x00007fde9df72eb0 @cstime=0.0, @cutime=0.0, @label="3:", @real=1.0552890002727509, @stime=0.0066349999999997245, @total=1.0511979999999999, @utime=1.0445630000000001>, | |
#<Benchmark::Tms:0x00007fdea3fea3d8 @cstime=0.0, @cutime=0.0, @label="4:", @real=0.09537400025874376, @stime=0.0004830000000000112, @total=0.0947919999999991, @utime=0.09430899999999909>] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
String#reverse
is clear winner.. it is implemented in C in the ruby source -> https://apidock.com/ruby/String/reverse