fastruby / fastruby/fast-ruby

Enumerable#sort_by is not always faster than #sort

Đang mở
#120 7 bình luận 0 reaction 0 người được giao Xem trên GitHub
Array Enumerable
Ngôn ngữ chính
Ruby
Star
5.7k
Fork
371
Chỉ số merge pull request
Không có pull request nào được merge trong 30 ngày

Mô tả

Per the Ruby 2.4.0 docs:

> The current implementation of sort_by generates an array of tuples containing the original collection element and the mapped value. This makes sort_by fairly expensive when the keysets are simple.

Here's a concrete example showing `sort` to be 2.70x faster in Ruby 1.9.3, 2.3.3 and 2.4.0:
```ruby
require 'benchmark/ips'

Benchmark.ips do |x|
x.time = 5
x.warmup = 2

ARRAY = %w{apple pear fig}

x.report("sort_by") do
ARRAY.sort_by(&:length)
end

x.report("sort") do
ARRAY.sort { |a, b| a.length <=> b.length}
end

x.compare!
end
```
```
Warming up --------------------------------------
sort_by 56.348k i/100ms
sort 111.946k i/100ms
Calculating -------------------------------------
sort_by 635.646k (±16.1%) i/s - 3.099M in 5.074036s
sort 1.713M (±16.3%) i/s - 8.284M in 5.023904s

Comparison:
sort: 1713232.1 i/s
sort_by: 635645.9 i/s - 2.70x slower
```

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Đánh giá

Issue này chưa được đánh giá.

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.