Posts

About

Crystal vs Ruby - Part 1 (Compilation and Speed)

September 14, 2015

Introduction

Crystal is a fairly new programming language that has the following goals:

  • Ruby’s efficiency for writing code by have nearly the same syntax
  • C’s efficiency for running code by compiling to efficient native code.

In this post, I will compare the compilation process of Ruby vs. Crystal and show of Crystal’s speed with a simple example.

Compilation

Ruby Ruby 1.9 introduced the Yet Another Ruby Virtual Machine (YARV) into its execution process. Before this Ruby was first parsed and then interpreted into native code. With the introduction of YARV, parsed Ruby code is actually compiled to YARV instructions and then interpreted into native code. This extra step in the process was able to improve speed.

ruby compiler

from Ruby Under a Microscope by Pat Shaughnessy

Crystal Crystal’s execution process is must simpler. It is parsed and then compiled directly into native code using LLVM. The compiler was originally written in Ruby but is now written in Crystal. This drastically reduced compile times

Fib Example

fib.rb

def fib(n)
	if n == 0 || n == 1
		n
	else
		fib(n-1) + fib(n-2)
	end
end

puts fib(ARGV[0].to_i)

fib.cr

def fib(n)
	if n == 0 || n == 1
		n
	else
		fib(n-1) + fib(n-2)
	end
end

puts fib(ARGV[0].to_i)

For this simple example, the code for computing a fibonacci number recursively in Ruby and Crystal are the same. Benchmarks done using ruby 2.2.0, crystal 0.7.7, and gcc 4.8.4. All times on the y-axis are in seconds.

fibonacci 30 ruby crystal

fibonacci 45 ruby crystal

Crystal is faster clearly than Ruby but how does it compare to C?

fibonacci 30 c crystal

fibonacci 45 c crystal

Now that is impressive!

Resources


Written by Jacob Oakes
I am a software architect who enjoys learning new things, clean code, and automated tests.