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
390
390
##### ` Enumerable#sort ` vs ` Enumerable#sort_by ` [ code] ( code/enumerable/sort-vs-sort_by.rb )
391
391
392
392
```
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]
395
395
396
396
Calculating -------------------------------------
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
399
400
-------------------------------------------------
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
402
404
403
405
Comparison:
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
406
409
```
407
410
408
411
Original file line number Diff line number Diff line change 1
- require ' benchmark/ips'
1
+ require " benchmark/ips"
2
2
3
3
User = Struct . new ( :name )
4
4
ARRAY = Array . new ( 100 ) do
5
5
User . new ( sprintf "%010d" , rand ( 1_000_000_000 ) )
6
6
end
7
7
8
- def slow
9
- ARRAY . sort { | a , b | a . name <=> b . name }
8
+ def fastest
9
+ ARRAY . sort_by ( & : name)
10
10
end
11
11
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 }
14
18
end
15
19
16
20
Benchmark . ips do |x |
21
+ x . report ( 'Enumerable#sort_by (Symbol#to_proc)' ) { fastest }
22
+ x . report ( 'Enumerable#sort_by' ) { faster }
17
23
x . report ( 'Enumerable#sort' ) { slow }
18
- x . report ( 'Enumerable#sort_by' ) { fast }
24
+
19
25
x . compare!
20
26
end
You can’t perform that action at this time.
0 commit comments