Created
April 7, 2017 18:04
-
-
Save eugene0707/56689995676c447bc02e7616e4a18bcd to your computer and use it in GitHub Desktop.
Anagram check 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
require 'benchmark' | |
string1 = 'старорежимность' | |
string2 = 'нерасторжимость' | |
N = 100000 | |
Benchmark.bm(30) do | x | | |
x.report('Sorted array equality') do | |
N.times { string1.chars.sort == string2.chars.sort } | |
end | |
x.report('Chars count (inject)') do | |
N.times { string1.chars.inject(Hash.new(0)){|h, c| h[c] += 1; h} == string2.chars.inject(Hash.new(0)){|h, c| h[c] += 1; h} } | |
end | |
x.report('Chars count (with_object)') do | |
N.times { string1.chars.each_with_object({}) {|c,ob| ob[c] = string1.count(c) if ob[c].nil?} == string2.chars.each_with_object({}) {|c,ob| ob[c] = string2.count(c) if ob[c].nil?} } | |
end | |
end | |
# Result: | |
# user system total real | |
# Sorted array equality 0.540000 0.000000 0.540000 ( 0.544768) | |
# Chars count (inject) 1.270000 0.000000 1.270000 ( 1.288586) | |
# Chars count (with_object) 3.700000 0.000000 3.700000 ( 3.742738) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment