-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Check slow hash accessing in
Array#sort
by `Performance/CompareWith…
…Block` Currently, `Performance/CompareWithBlock` cop accepts the following code. ```ruby array.sort { |a, b| a[:foo] <=> b[:foo] } ``` But the code has same issue as `a.foo <=> b.foo`. So, by this change, the cop registers an offense for this code. Benchmark ======== ```ruby require 'benchmark' array10000 = 10000.times.map do |i| {value: i} end.shuffle array100 = 100.times.map do |i| {value: i} end.shuffle array10 = 10.times.map do |i| {value: i} end.shuffle Benchmark.bm(15) do |x| x.report('sort_by 10000'){500.times{array10000.sort_by{|a| a[:value]}}} x.report('sort 10000'){500.times{array10000.sort{|a, b| a[:value] <=> b[:value]}}} x.report('sort_by 100'){50000.times{array100.sort_by{|a| a[:value]}}} x.report('sort 100'){50000.times{array100.sort{|a, b| a[:value] <=> b[:value]}}} x.report('sort_by 10'){500000.times{array10.sort_by{|a| a[:value]}}} x.report('sort 10'){500000.times{array10.sort{|a, b| a[:value] <=> b[:value]}}} end ``` ```bash $ ruby test.rb user system total real sort_by 10000 2.470000 0.000000 2.470000 ( 2.480009) sort 10000 4.790000 0.010000 4.800000 ( 4.797943) sort_by 100 1.140000 0.000000 1.140000 ( 1.146861) sort 100 1.910000 0.000000 1.910000 ( 1.910717) sort_by 10 0.880000 0.000000 0.880000 ( 0.871086) sort 10 1.000000 0.000000 1.000000 ( 1.002856) ```
- Loading branch information
Showing
4 changed files
with
115 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters