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:
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

Ahh, yeah. I would still like to do that. I was searching around Google on parsers for csv. That's where I realized that what seems deceptively simple is actually horrible complex (hundreds of lines). That is where I got unsure about how to tackle this exactly. At least for someone who has only read a couple of books on C, but never written more than a 10-liner.
As for the implemtation, I thought about subclassing FasterCSV. class ReallyFasterCSV < FasterCSV, so that the FaterCSV package is actually untouched and the ReallyFasterCSV package can be its own gem for people to download if they know that they have a compiler setup that works with Inline.
I really need to brush up on my C. Every time I start I realize that it's not really that much fun.
Sascha Ebach