Prev | Current Page 273 | Next

Brad Ediger

"Advanced Rails"

In addition, most scripting languages
have a rich set of community-developed libraries available. Though CPAN
(Perl??™s collection of third-party libraries) is the undisputed champion in this arena,
Ruby has Rubyforge (http://rubyforge.org) and the Ruby Application Archive (http://
raa.ruby-lang.org/).
Writing inline C code
Writing Ruby extensions in C used to be hard. If you wanted to rewrite performancesensitive
functions, there were many things besides the actual code that you had to
deal with. Not so anymore.
Ryan Davis has unleashed an incredible tool, RubyInline,??  for integrating C with
Ruby. This tool allows you to embed C/C++ code as strings directly within an application.
The strings are then compiled into native code (only to be recompiled when
they change) and installed into your classes. The canonical example, the factorial
function, shows just how fast and clean this can be:
require 'rubygems'
require 'inline' # gem install RubyInline
require 'benchmark'
class Test
# Standard Ruby factorial function
* http://www.loudthinking.com/arc/000598.html
??  http://www.zenspider.com/ZSS/Products/RubyInline/Readme.html
Other Systems | 183
def factorial(n)
result = 1
n.downto(2) { |x| result *= x }
result
end
# Reimplemented in C (compiled on the fly)
inline do |builder|
builder.c <<-EOINLINE
long factorial_c(int max) {
int i = max,
result = 1;
while (i >= 2) { result *= i--; }
return result;
}
EOINLINE
end
end
We can then set up a benchmark to compare the two implementations:
t = Test.


Pages:
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285