“ranking” is always an integer. So if I have an array of these objects,
say, @allApplications how do I sort using each application’s ranking
(@application.ranking)?
Benchmark.bm do |bmark|
bmark.report(“Sort”) { applications.sort }
bmark.report(“Sort By”) {applications.sort_by {|o| o.ranking}}
end
C:\Documents and Settings\flifson\Desktop>ruby sort_test.rb
user system total real
Sort 20.782000 0.031000 20.813000 ( 20.844000)
Sort By 6.687000 0.000000 6.687000 ( 6.687000)
I don’t understand, can someone please explain this loss of speed?
Sorting compares pairs of objects many more times than the number of
objects actually being sorted. The <=> method extracts the ranking
from the objects each time a pair is compared. The sort_by method only
extracts the ranking from each object once then compares these. The
time difference represents the overhead of the <=> method call and the
time required to retrieve instance variables for each of the pair.