RubyFlow The Ruby and Rails community linklog

×

The Ruby and Rails community linklog

Made a library? Written a blog post? Found a useful tutorial? Share it with the Ruby community here or just enjoy what everyone else has found!

How Closures Behave in Ruby

Comments

Just for the heck of it, I was curious how closures performed in Ruby. The case is similar for 1.8 and 1.9.

def counter count = 0 return lambda { count += 1 } end

c = counter </code>

class Counter attr :count

def initialize @count = 0 end

def call @count += 1 end end

c = Counter.new </code>

Doing a million iterations:

user system total real 0.900000 0.010000 0.910000 ( 0.945943) 0.470000 0.000000 0.470000 ( 0.489510)

Clearly classes are a faster way to make a counter…

Memory usage is even more different. The following is after allocation of a million of these little counters:

TIME RPRVT RSHRD RSIZE VSIZE 0:05.85 315M 1.14M 316M 352M 0:01.86 108M 1.16M 108M 144M

Merely thought it was interesting and wanted to share :)

Post a comment

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in