Skip to content

Commit

Permalink
Merge pull request fastruby#176 from sshaw/master
Browse files Browse the repository at this point in the history
Add Array#sort.reverse vs Array#sort_by with block
  • Loading branch information
etagwerker authored Feb 20, 2023
2 parents 54c0c6e + 3c00f22 commit 7c87d13
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,27 @@ Comparison:
Fixnum#times + map: 678097.4 i/s - 1.58x slower
```

##### `Array#sort.reverse` vs `Array#sort_by` + block [code](code/array/sort-reverse-vs-sort_by-with-block.rb)

```
$ ruby -v code/array/sort-reverse-vs-sort_by.rb
ruby 2.5.2p104 (2018-10-18 revision 65133) [x86_64-darwin13]
Warming up --------------------------------------
Array#sort.reverse
16.231k i/100ms
Array#sort_by &:-@
5.406k i/100ms
Calculating -------------------------------------
Array#sort.reverse
149.492k (±11.0%) i/s - 746.626k in 5.070375s
Array#sort_by &:-@
51.981k (± 8.8%) i/s - 259.488k in 5.041625s
Comparison:
Array#sort.reverse: 149492.2 i/s
Array#sort_by &:-@: 51980.6 i/s - 2.88x (± 0.00) slower
```

### Enumerable

##### `Enumerable#each + push` vs `Enumerable#map` [code](code/enumerable/each-push-vs-map.rb)
Expand Down
18 changes: 18 additions & 0 deletions code/array/sort-reverse-vs-sort_by-with-block.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
require "benchmark/ips"

ARRAY = 100.times.map { rand(1_000_000_000) }

def fast
ARRAY.sort.reverse
end

def slow
ARRAY.sort_by(&:-@)
end

Benchmark.ips do |x|
x.report('Array#sort.reverse') { fast }
x.report('Array#sort_by &:-@') { slow }

x.compare!
end

0 comments on commit 7c87d13

Please sign in to comment.