Skip to content
July 20, 2007 / hellonico

Faster ruby

After reading a post on symbols, I went on doing my own experiment. Here’s what came out:

h[:cool] = :hello

will execute approximately 2 times as fast as:

h["cool"] = :hello

The original post pointed out that symbols are never garbage collected but given the low memory footprint of Ruby, might as well get the extra speed.

An other experiment I did some time ago, if you declare:

module Niko MY_CONST = “this is a string for testing” end

and then try to access it:

Niko::MY_CONST

will be slightly slower than doing:

include Niko MY_CONST

Amusingly enough, this appears to be untrue on jruby. (confirmed that the same behavior is on both plateform, see next post)

2 Comments

Leave a Comment
  1. Charles Oliver Nutter / Jul 20 2007 4:43 am

    The second example is somewhat surprising to me. In the first case, if Niko is a constant in the current module/class namespace, it will do a single lookup to find it, followed by a single lookup in the Niko namespace to find MY_CONST. In the second example, it will first search the current module or class for MY_CONST and then search the included module for MY_CONST. Both cases work out to two constant hash lookups, so it’s strange that one would be faster in Ruby than the other…

  2. hellonico / Jul 20 2007 5:27 am

    Charles,

    Thank you for your comments and insight.

    I went back and ran the experiment again:
    http://hellohellonico.wordpress.com/2007/07/20/faster-ruby2

    I wonder what makes those two tests behaving differently from a jruby point of view.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.