Created
April 6, 2015 08:29
-
-
Save ravicious/b5d81e369cbd1d8518a5 to your computer and use it in GitHub Desktop.
Hash[] vs Array#to_h
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/ips' | |
| DEFAULT_CHARSET = ('a'..'z').to_a + (0..9).to_a | |
| def random_symbol | |
| charset = ('a'..'z') | |
| random_string(charset).to_sym | |
| end | |
| def random_string(charset = DEFAULT_CHARSET) | |
| length = rand(10) + 3 | |
| length.times.map { charset.to_a.sample }.join | |
| end | |
| NESTED_ARRAY = 1000.times.map { [random_symbol, random_string] } | |
| FLAT_ARRAY = NESTED_ARRAY.flatten | |
| Benchmark.ips do |x| | |
| x.report('Hash[] nested array', 'Hash[NESTED_ARRAY]') | |
| x.report('Hash[] flat array', 'Hash[*FLAT_ARRAY]') | |
| x.report('Array#to_h', 'NESTED_ARRAY.to_h') | |
| x.compare! | |
| end |
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
| Calculating ------------------------------------- | |
| Hash[] nested array 174.000 i/100ms | |
| Hash[] flat array 186.000 i/100ms | |
| Array#to_h 204.000 i/100ms | |
| ------------------------------------------------- | |
| Hash[] nested array 2.058k (±24.2%) i/s - 9.222k | |
| Hash[] flat array 2.140k (±23.7%) i/s - 9.672k | |
| Array#to_h 2.008k (±21.5%) i/s - 9.588k | |
| Comparison: | |
| Hash[] flat array: 2139.9 i/s | |
| Hash[] nested array: 2057.8 i/s - 1.04x slower | |
| Array#to_h: 2008.2 i/s - 1.07x slower |
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
| hash_bench: ruby -v | |
| ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-darwin14] | |
| hash_bench: system_profiler SPHardwareDataType | |
| Hardware: | |
| Hardware Overview: | |
| Model Name: MacBook Pro | |
| Model Identifier: MacBookPro11,1 | |
| Processor Name: Intel Core i5 | |
| Processor Speed: 2,6 GHz | |
| Number of Processors: 1 | |
| Total Number of Cores: 2 | |
| L2 Cache (per Core): 256 KB | |
| L3 Cache: 3 MB | |
| Memory: 8 GB |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment