File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -457,6 +457,25 @@ Comparison:
457457 Hash#merge: 409.6 i/s - 24.00x slower
458458```
459459
460+ ##### ` Hash#sort_by ` vs ` Hash#sort ` [ code] ( code/hash/hash-key-sort_by-vs-sort.rb )
461+
462+ To sort hash by key.
463+
464+ ```
465+ $ ruby -v code/hash/hash-key-sort_by-vs-sort.rb
466+ ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-darwin14]
467+
468+ Calculating -------------------------------------
469+ sort_by + to_h 11.468k i/100ms
470+ sort + to_h 8.107k i/100ms
471+ -------------------------------------------------
472+ sort_by + to_h 122.176k (± 6.0%) i/s - 619.272k
473+ sort + to_h 81.973k (± 4.7%) i/s - 413.457k
474+
475+ Comparison:
476+ sort_by + to_h: 122176.2 i/s
477+ sort + to_h: 81972.8 i/s - 1.49x slower
478+ ```
460479
461480### Proc & Block
462481
Original file line number Diff line number Diff line change 1+ require "benchmark/ips"
2+
3+ HASH = Hash [ *( "a" .."z" ) . to_a . shuffle ]
4+
5+ def fast
6+ HASH . sort_by { |k , _v | k } . to_h
7+ end
8+
9+ def slow
10+ HASH . sort . to_h
11+ end
12+
13+ Benchmark . ips do |x |
14+ x . report ( "sort_by + to_h" ) { fast }
15+ x . report ( "sort + to_h" ) { slow }
16+ x . compare!
17+ end
You can’t perform that action at this time.
0 commit comments