Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Crystal faster than Ruby?

Tags:

I would very much like to know what exactly makes Crystal faster than Ruby while code is so similar. The short answer could be that it is compiled, and Ruby is interpreted, yet I would like to understand more about the language specifications.

like image 206
Marcelo Boeira Avatar asked Feb 22 '16 12:02

Marcelo Boeira


People also ask

What is the difference between Ruby and Crystal?

Developers describe Crystal as "Fast as C, slick as Ruby". Crystal is a programming language that resembles Ruby but compiles to native code and tries to be much more efficient, at the cost of disallowing certain dynamic aspects of Ruby.

Why is Ruby considered slow?

The answer is simple: people say ruby is slow because it is slow based on measured comparisons to other languages.

How fast is Crystal language?

The results show that Crystal can be considered a fast programming language. While C with all optimisations of gcc is still faster, the per- formance of Crystal is comparable with Go. As expected is Ruby, with just-in-time (JIT) compilation or without, by a factor of 8 respectively 9 slower than Crystal.

Is Ruby a Crystal?

Crystal, on the other hand, comes with all the good parts of Ruby but none of its drawbacks. Crystal's syntax is almost identical to Ruby's. This code snippet is identical for both Ruby and Crystal. Due to the similar syntax, it is an absolute breeze to migrate from one to the other.


1 Answers

I guess it's a combination of things:

  • Ruby is interpreted, and the interpreter could be improved. For example other interpreted languages like JS or Java have a very good VM and JIT compiler.
  • Many Ruby checks that are done at runtime, in Crystal are done at compile time. For example a simple method call in Ruby ends up in a method lookup. Even with a cache it won't beat a native function call. Or when Ruby decides to do different things based on the type of an argument, these checks are done at runtime. In Crystal they are known at compile time so those checks disappear. Without those checks the compiler can inline calls and do some pretty crazy stuff (thanks to LLVM). Or, for example, looking up an instance varaibles is a hash lookup in Ruby (as far as I know), while in Crystal it's just a memory indirection and load.
  • In Crystal we try to avoid extra memory allocations. For example to_s(io) writes to an IO instead of converting the object to a string in memory. Or we have tuples for fixed-sized arrays that are allocated on the stack. Or you can declare a type as a struct to avoid heap allocations.
  • Calls to C are done directly, without wrappers. Well, you could have a wrapper but that will be inlined by LLVM. In Ruby it always has to resolve a Ruby method first.

Probably there are many more reasons, but they are related.

like image 96
asterite Avatar answered Sep 18 '22 23:09

asterite