File tree Expand file tree Collapse file tree 2 files changed +23
-14
lines changed Expand file tree Collapse file tree 2 files changed +23
-14
lines changed Original file line number Diff line number Diff line change @@ -390,19 +390,22 @@ Enumerable#select.last: 119386.8 i/s - 10.58x slower
390390##### ` Enumerable#sort ` vs ` Enumerable#sort_by ` [ code] ( code/enumerable/sort-vs-sort_by.rb )
391391
392392```
393- $ ruby -v code/enumerable/sort-vs-sort_by.rb
394- ruby 2.2.0p0 (2014-12-25 revision 49005 ) [x86_64-darwin14]
393+ ruby -v code/enumerable/sort-vs-sort_by.rb
394+ ruby 2.2.2p95 (2015-04-13 revision 50295 ) [x86_64-darwin14]
395395
396396Calculating -------------------------------------
397- Enumerable#sort 1.158k i/100ms
398- Enumerable#sort_by 2.401k i/100ms
397+ Enumerable#sort_by (Symbol#to_proc) 2.680k i/100ms
398+ Enumerable#sort_by 2.462k i/100ms
399+ Enumerable#sort 1.320k i/100ms
399400-------------------------------------------------
400- Enumerable#sort 12.140k (± 4.9%) i/s - 61.374k
401- Enumerable#sort_by 24.169k (± 4.0%) i/s - 122.451k
401+ Enumerable#sort_by (Symbol#to_proc) 25.916k (± 4.4%) i/s - 131.320k
402+ Enumerable#sort_by 24.650k (± 5.1%) i/s - 125.562k
403+ Enumerable#sort 14.018k (± 5.6%) i/s - 69.960k
402404
403405Comparison:
404- Enumerable#sort_by: 24168.9 i/s
405- Enumerable#sort: 12139.8 i/s - 1.99x slower
406+ Enumerable#sort_by (Symbol#to_proc): 25916.1 i/s
407+ Enumerable#sort_by: 24650.2 i/s - 1.05x slower
408+ Enumerable#sort: 14018.3 i/s - 1.85x slower
406409```
407410
408411
Original file line number Diff line number Diff line change 1- require ' benchmark/ips'
1+ require " benchmark/ips"
22
33User = Struct . new ( :name )
44ARRAY = Array . new ( 100 ) do
55 User . new ( sprintf "%010d" , rand ( 1_000_000_000 ) )
66end
77
8- def slow
9- ARRAY . sort { | a , b | a . name <=> b . name }
8+ def fastest
9+ ARRAY . sort_by ( & : name)
1010end
1111
12- def fast
13- ARRAY . sort_by ( &:name )
12+ def faster
13+ ARRAY . sort_by { |element | element . name }
14+ end
15+
16+ def slow
17+ ARRAY . sort { |a , b | a . name <=> b . name }
1418end
1519
1620Benchmark . ips do |x |
21+ x . report ( 'Enumerable#sort_by (Symbol#to_proc)' ) { fastest }
22+ x . report ( 'Enumerable#sort_by' ) { faster }
1723 x . report ( 'Enumerable#sort' ) { slow }
18- x . report ( 'Enumerable#sort_by' ) { fast }
24+
1925 x . compare!
2026end
You can’t perform that action at this time.
0 commit comments