views:

174

answers:

4

I'm currently writing a C extension for ruby as part of a project of mine. The extension is to implement an algorithm I have already working in ruby in C for performance reasons. The question I pose though is whether I should use ruby's own data types in the C code or convert them to C's native types for performance reasons?

Would such a conversion make a huge difference?

Thanks in advance

Patrick

+3  A: 

In principle, your snippet of C code should use C data structures to run faster. How much faster will it run depends on how much data the data structures will hold (and how many times the snippet of C code will go through them).

The more passes through the data the more you will notice the performance inprovenment of using native C data structures.

lordsandwich
A: 

For maximal performance, I think it's better to rewrite it completely in C, and just keep a minimal glue level of Ruby-C (Ruby C API data structures and calls) in between.

Eli Bendersky
A: 

Only use Ruby data types if you need to access that data from Ruby.

banister
A: 

Good answers. I would only suggest whatever you do, you wrap a temporary loop around it of 10^3 or 10^6 times and tune the daylights out of it, then remove the outer loop. Here's an example of what I mean. Just because it's in C doesn't guarantee it's as fast as possible.

Mike Dunlavey