24

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.

4

1 回答 1

45

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.

于 2016-02-22T14:56:08.197 回答