File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change @@ -552,6 +552,30 @@ Comparison:
552552 Array#reverse.each: 190729.1 i/s - 1.13x slower
553553```
554554
555+ ##### ` Enumerable#sort_by.first ` vs ` Enumerable#min_by ` [ code] ( code/enumerable/sort_by-first-vs-min_by.rb )
556+ ` Enumerable#sort_by ` performs a sort of the enumerable and allocates a
557+ new array the size of the enumerable. ` Enumerable#min_by ` doesn't
558+ perform a sort or allocate an array the size of the enumerable.
559+ Similar comparisons hold for ` Enumerable#sort_by.last ` vs `
560+ ` Enumerable#max_by ` , ` Enumerable#sort.first ` vs ` Enumerable#min ` , and
561+ ` Enumerable#sort.last ` vs ` Enumerable#max ` .
562+
563+ ```
564+ ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin17]
565+ Warming up --------------------------------------
566+ Enumerable#min_by 15.170k i/100ms
567+ Enumerable#sort_by...first
568+ 10.413k i/100ms
569+ Calculating -------------------------------------
570+ Enumerable#min_by 157.877k (± 0.9%) i/s - 804.010k in 5.093048s
571+ Enumerable#sort_by...first
572+ 106.831k (± 1.3%) i/s - 541.476k in 5.069403s
573+
574+ Comparison:
575+ Enumerable#min_by: 157877.0 i/s
576+ Enumerable#sort_by...first: 106831.1 i/s - 1.48x slower
577+ ```
578+
555579##### ` Enumerable#detect ` vs ` Enumerable#select.first ` [ code] ( code/enumerable/select-first-vs-detect.rb )
556580
557581```
Original file line number Diff line number Diff line change 1+ require 'benchmark/ips'
2+
3+ ARRAY = [ *1 ..100 ]
4+
5+ def fast
6+ ARRAY . min_by { |x | x . succ }
7+ end
8+
9+ def slow
10+ ARRAY . sort_by { |x | x . succ } . first
11+ end
12+
13+ Benchmark . ips do |x |
14+ x . report ( 'Enumerable#min_by' ) { fast }
15+ x . report ( 'Enumerable#sort_by...first' ) { slow }
16+ x . compare!
17+ end
You can’t perform that action at this time.
0 commit comments