Created
September 13, 2017 03:21
-
-
Save kaityo256/3b777365a81b153e9aac0ec74d13da52 to your computer and use it in GitHub Desktop.
Slice string every 10th character
This file contains hidden or 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
| require 'benchmark' | |
| def usescan(input) | |
| input.each do |s| | |
| a = s.scan(/.{1,10}/) | |
| end | |
| end | |
| def useslice(input) | |
| input.each do |s| | |
| a = s.each_char.each_slice(10).map(&:join) | |
| end | |
| end | |
| srand(1) | |
| input = Array.new(10) do | |
| s = "" | |
| 1000000.times do | |
| s << (rand*10).to_i.to_s | |
| end | |
| s | |
| end | |
| r1 = Benchmark.realtime do | |
| usescan(input) | |
| end | |
| r2 = Benchmark.realtime do | |
| useslice(input) | |
| end | |
| puts "scan #{r1} [sec]" # => scan 0.34344600001350045 [sec] | |
| puts "slice #{r2} [sec]" # => slice 2.0583080000360496 [sec] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment