Dominik Honnef

Ruby benchmarks

The following is a list of benchmarks done with the Ruby programming language, mostly showing that different ways of doing the same thing actually can have quite an impact on the overall performance of your code. And because this list is by no means “complete” or “rich” yet, you are asked to post your own benchmarks, which will then be added to this article.

These benchmarks were all made on a same system with the following setup:

System
Gentoo, 2.6.29, Pentium 4, 3.20GHZ
Ruby
ruby 1.9.1p243 (2009-07-16 revision 24175) [i686-linux]

Last update: 2009/11/27

Subject Link Conclusion
Check if a string contains a certain character gist include? is the most natural and fastet way.
Does slicing an array really cost us much? gist No.
Single-quoted vs. double-quoted strings gist When no interpolation is used, both kind of strings are equally fast.
Split: Regexp vs. String gist Strings are faster.
Replacing a single character: gsub vs. tr gist tr is way faster.
Deleting a single character: gsub vs. tr vs. delete gist No difference between delete and tr, gsub is again slower.
Deleting multiple characters: gsub vs. tr vs. delete gist A chain of deletes isn’t only ugly, but slow as well. tr wins again over gsub, isn’t any faster than delete though.
gsub: Regexp vs String Derived from the tests with replacing a character gsub is faster when used with regexps.
Construcing regexps gist When possible use literal regexps.
String interpolation in regexps gist Regexp.new seems to be slightly faster, if you need it to be interpolated every run.
Matching regexps gist =~ is faster than match, because it does not have to create a MatchData object.
Structs: Inheritance vs. assignment gist No noticeable difference.
A comparison of YAML and Marshal Link