The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
#sort_by and #sort_obj

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Eric Hodel

Posts: 660
Nickname: drbrain
Registered: Mar, 2006

Eric Hodel is a long-time Rubyist and co-founder of Seattle.rb.
#sort_by and #sort_obj Posted: Oct 7, 2007 2:10 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Eric Hodel.
Original Post: #sort_by and #sort_obj
Feed Title: Segment7
Feed URL: http://blog.segment7.net/articles.rss
Feed Description: Posts about and around Ruby, MetaRuby, ruby2c, ZenTest and work at The Robot Co-op.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Eric Hodel
Latest Posts From Segment7

Advertisement

I was speeding up RubyGems and found a bunch of places that still used #sort instead of #sort_by. #sort_by is faster than #sort because it performs fewer comparisons resulting in fewer method calls.

All these places were external to the thing I was sorting, so they’d need to know how to perform the sorting, which is just plain wrong. I did a bit of thinking, and created a #sort_obj method to return an object that can be used for sorting instead.

So Gem::Specification#<=> went from:

def <=>(other)
  platform_num = platform == Gem::Platform::RUBY ? -1 : 1
  other_platform_num = other.platform == Gem::Platform::RUBY ? -1 : 1

  [@name, @version, platform_num] <=>
    [other.name, other.version, other_platform_num]
end

To:

def sort_obj
  [@name, @version.to_ints, @platform == Gem::Platform::RUBY ? -1 : 1]
end

def <=>(other)
  sort_obj <=> other.sort_obj
end

So now instead of:

specs.sort_by do |spec|
  [@name, @version.to_ints, @platform == Gem::Platform::RUBY ? -1 : 1]
end

I can write:

specs.sort_by { |spec| spec.sort_obj }

Read: #sort_by and #sort_obj

Topic: Object removal using seam carving, still fast Previous Topic   Next Topic Topic: Calling on the GC after Rubygems

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use