fast-ruby icon indicating copy to clipboard operation
fast-ruby copied to clipboard

Add Array#sort.reverse vs Array#sort_by with block

Open sshaw opened this issue 6 years ago • 7 comments

sshaw avatar May 26 '19 22:05 sshaw

Should really be compared with sort_by{ |a| -a }or sort_by(&:-@)

semaperepelitsa avatar Jul 17 '20 16:07 semaperepelitsa

arr.reverse.sort simply makes no sense. Array#reverse returns reverse-ordered copy of an array.

Comparing sort_by { |a| -a } to sort_by(&:-@) was already covered in:

https://github.com/JuanitoFatas/fast-ruby/blob/master/code/enumerable/sort-vs-sort_by.rb

Comparing sort { |a, b| b <=> a } to sort_by(&:-@) is also pointless as it's already covered by the above.

ixti avatar Jul 31 '20 22:07 ixti

Did you mean, sort.reverse!?

ParadoxV5 avatar Aug 01 '20 01:08 ParadoxV5

Should really be compared with sort_by{ |a| -a }or sort_by(&:-@)

@semaperepelitsa agreed. Updated.

arr.reverse.sort simply makes no sense.

@ixti typo, should be arr.sort.reverse. Fixed.

Comparing sort_by { |a| -a } to sort_by(&:-@) was already covered in:

@ixti yes I know, I wrote it. This PR differs by 50%.

Did you mean, sort.reverse!?

@ParadoxV5 yes updated (though no !)

sshaw avatar Aug 01 '20 02:08 sshaw

Though technically this is comparing Array#sort etc... not Enumerable. Updated.

sshaw avatar Aug 01 '20 02:08 sshaw

though no !

@sshaw Not sure if the sort! variant is faster or not because several other languages (including our rival Python) do their sorting in-place (modifying the original). (reverse and sort each creates a new array with reversed contents.)

Also, should compare with _2 <=> _1 because Numeric happens to have negation functionality (@-), but not guaranteed any ~~Comparable~~ duck-type with <=>, such as Strings (@- doesn’t negate) and Arrays (@- isn’t defined). (P.P.S Though we can include Numeric reverse-sorting separately as a special case.)

P.S. @ixti The above file does not sort reversedly.

ParadoxV5 avatar Aug 01 '20 05:08 ParadoxV5

I still think this comparison is weird and very niche - it has meaning only when the object is an Array of Numbers. In which case the bet variant will be: arr.sort.tap(&:reverse!), in other cases it will either fail or will give unexpected result.

@ParadoxV5 I know that the sort-vs-sort_by.rb has no reverse sorting.

ixti avatar Aug 04 '20 00:08 ixti