🕷 zenspider.com

by ryan davis



sitemap
Looking for the Ruby Quickref?

Best of both worlds

Published 2006-03-07 @ 03:47

Tagged rubyinline

Here is my very simple rule for optimizing:

Never ever code for speed until you need to code for speed!

Consider it an addendum to Knuth’s “root of all evil” law. There are two corollaries to this law:

Always measure.

and

Only rewrite the slow part in C, not the whole damn thing.

Some of this came up recently because of a dialog last week on ruby-talk between Sascha Ebach and JEG2 about making FasterCSV even faster. James wants to keep the module as pure ruby (totally laudable goal) but Sascha thought it’d be neat to take advantage of RubyInline if it were available. I’m all for keeping it pure ruby, but I wanted to see how you’d do the dual implementation version in a way that still read clean. Here is my first scratch at it:

1
2
3
4
5
6
7
8
9
10
11
12
13
 begin; require 'inline'; rescue LoadError; end  
  
 class MaybeFast  
   def blah  
     puts "slow version"  
   end unless respond_to? :inline  
  
   inline do |builder|  
     builder.c 'void blah() { puts("fast version"); }'  
   end if respond_to? :inline  
 end  
  
 MaybeFast.new.blah