RubyのAOTコンパイラって何だ? / What Is Ruby’s AOT Compiler?
まつもと ゆきひろさんがRubyのAOT(Ahead Of Time:事前)コンパイラ「Spinel」をリリースされましたね。
Yukihiro Matsumoto (Matz), the creator of Ruby, has released an AOT (Ahead Of Time) compiler for Ruby called “Spinel.”
これの開発エピソードが日経ソフトウェア2026年9月号の「プログラミング質問箱」に書かれていて、とても面白くてためになりました! 神回でした! Matz、やってくれるぜ!
The development story behind Spinel was featured in the “Programming Q&A” column of the September 2026 issue of Nikkei Software. It was fascinating and incredibly informative! What an episode! Matz, you’ve done it again!
Rubyってインタープリタ言語ですよね?
Ruby is an interpreted language, right?
事前「コンパイラ」とは?
So, what exactly is an “ahead-of-time compiler”?
なんと、これによって
Apparently, this makes it possible to compile:
Ruby → C言語 → バイナリファイル
Ruby → C → Binary executable
これができると
With this approach, we can address:
-
Ruby成果物配布の課題(ここでは動くけどあっちでは動かない)
The challenges of distributing Ruby applications (“It works on my machine, but not on yours!”)
さらに、
And on top of that:
-
Ruby成果物の速度アップ(こちとらバイナリですから)
Faster Ruby applications (Hey, we’re talking about native binaries here!)
すげえじゃねえか何だそれ!
That’s incredible! What the heck is this thing?!
Spinelを使ったらRubyが速くなるか確かめてみた / Does Spinel Make Ruby Faster?
手前味噌ではありますが、題材として以下の記事とまったく同じ問題「最小自由数」を同じ環境で解きました。
For this experiment, I used exactly the same problem, “Minimum Free Number,” as in the following article, running it in the same environment.
99999件のデータを入力し、正しい答え69918にたどり着く処理を、「素のRubyのみ」と「Ruby + Spinel」で10万回ずつ行い、平均処理速度を見比べてみました。
I ran the computation that takes 99,999 input values and finds the correct answer, 69,918, 100,000 times using plain Ruby and another 100,000 times using Ruby + Spinel. Then I compared their average execution times.
- 確認環境 / Test Environment
| 項目 / Item | 内容 / Contents |
|---|---|
| OS | Fedora 41 (x86_64) |
| CPU | Intel(R) Core(TM) i3-4130 CPU @ 3.40GHz |
| Memory | 8GB |
素のRubyのみ / Plain Ruby
- 確認環境 / Environment
~/Ruby/spinel/myapp/bin$ ruby --version
ruby 3.3.10 (2025-10-23 revision 343ea05002) [x86_64-linux]
- 測定対象プログラム / Benchmark Program
# myapp_cruby.rb
require_relative 'input_min_free'
def minfrom(a, n, xs)
return a if n == 0
b = a + 1 + n / 2
us, vs = xs.partition { |x| x < b }
m = us.length
if m == b - a
minfrom(b, n - m, vs)
else
minfrom(a, m, us)
end
end
def minfree(xs)
minfrom(0, xs.length, xs)
end
sum = 0.0
best = Float::INFINITY
worst = 0.0
best_count = 0
worst_count = 0
ans = 0
100000.times do |i|
# 入力データ99999件は別ファイル input_min_free.rb に定義
v2 = InputMinFree::INPUT_MIN_FREE.dup
start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
ans = minfree(v2)
end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
cur = end_time - start_time
best, best_count = cur, i if cur < best
worst, worst_count = cur, i if cur > worst
sum += cur
end
puts "result:#{ans}"
puts "sum = %.6f sec." % sum
puts "ave = %.6f sec." % (sum / 100000)
puts "best = %.6f sec." % best
puts "best_count = #{best_count}"
puts "worst = %.6f sec." % worst
puts "worst_count = #{worst_count}"
- 測定結果 / Results
10万回測定平均 約18msでした。
The average execution time over 100,000 runs was approximately 18 ms.
~/Ruby$ ruby myapp_cruby.rb
result:69918
sum = 0.181034 sec.
ave = 0.018103 sec.
best = 0.017671 sec.
best_count = 5
worst = 0.018359 sec.
worst_count = 9
Ruby + Spinel
- 確認環境 / Environment
~/Ruby/spinel/myapp/bin$ ruby --version
ruby 3.3.10 (2025-10-23 revision 343ea05002) [x86_64-linux]
/Ruby/spinel/myapp/bin$ spin --version
spin 2026.09.12+29 (fa630b1f) [gcc 14.3.1 (cc)]
- 測定対象プログラム / Benchmark Program
# frozen_string_literal: true
require_relative 'input_min_free'
# 処理時間測定にはCライブラリを使用
module LibC
ffi_func :clock, [], :long
ffi_const :CLOCKS_PER_SEC, 1_000_000
end
def minfrom(a, n, xs)
return a if n == 0
b = a + 1 + n / 2
us, vs = xs.partition { |x| x < b }
m = us.length
if m == b - a
minfrom(b, n - m, vs)
else
minfrom(a, m, us)
end
end
def minfree(xs)
minfrom(0, xs.length, xs)
end
sum = 0.0
best = Float::INFINITY
worst = 0.0
best_count = 0
worst_count = 0
ans = 0
1000_00.times do |i|
# 入力データ99999件は別ファイル input_min_free.rb に定義
v2 = InputMinFree::INPUT_MIN_FREE.dup
start_time = LibC.clock()
ans = minfree(v2)
end_time = LibC.clock()
# clock() の差分を秒に換算
cur = (end_time - start_time).to_f / LibC::CLOCKS_PER_SEC
if best > cur
best = cur
best_count = i
end
if worst < cur
worst = cur
worst_count = i
end
sum += cur
end
puts "result:#{ans}"
puts "sum = %.6f sec." % sum
puts "ave = %.6f sec." % (sum / 100_000)
puts "best = %.6f sec." % best
puts "best_count = #{best_count}"
puts "worst = %.6f sec." % worst
puts "worst_count = #{worst_count}"
- 測定結果 / Results
10万回測定平均 約3.6msでした。
The average execution time over 100,000 runs was approximately 3.6 ms.
~/Ruby/spinel/myapp/bin$ spinel myapp.rb -o myapp
./myapp
myapp.rb -> myapp
result:69918
sum = 368.427699 sec.
ave = 0.003684 sec.
best = 0.003282 sec.
best_count = 22
worst = 0.007330 sec.
worst_count = 14944
Ruby と Spinel の速度比較結果 / Ruby vs. Spinel: Performance Comparison
筆者の題材(最小自由数)と環境では、SpinelでコンパイルしたRubyプログラムは、素のRubyとして実行した場合と比べて約5倍高速でした!
In my environment, using the Minimum Free Number problem, the Ruby program compiled with Spinel ran approximately five times faster than the same program executed with plain Ruby!
| 環境 / Environment | バージョン / Version | 10万回の平均処理速度[ms] / Average Time |
|---|---|---|
| Ruby | ruby 3.3.10 (2025-10-23 revision 343ea05002) [x86_64-linux] | 18.103 |
| Ruby + Spinel | spin 2026.09.12+29 (fa630b1f) [gcc 14.3.1 (cc)] | 3.684 |
Spinelが何をしているのか調べてみた / Investigating What Spinel Actually Does
RubyをCにするって結局何だ?
So, what does it actually mean to turn Ruby into C?
ていうか無理だろ。Rubyは動的型付けインタープリタ言語、Cは静的型付けコンパイル言語だぞ?
Wait, isn’t that impossible? Ruby is a dynamically typed, interpreted language, while C is a statically typed, compiled language!
じゃあさっき速くなったあれは何だ? いったい俺は何をされたんだ!?
Then what was that thing that just got faster? What on earth happened under the hood?!
…速くなったってどれくらいだっけ?
…Speaking of which, how fast was it again?
前回の記事で最速だったC++と比較してみよう。
Let’s compare it with C++, which was the fastest language in my previous article.
| 環境 / Environment | バージョン / Version | 10万回の平均処理速度[ms] / Average Time |
|---|---|---|
| Ruby + Spinel | spin 2026.09.12+29 (fa630b1f) [gcc 14.3.1 (cc)] | 3.684 |
| C++ | gcc (GCC) 14.3.1 20250808 (Red Hat 14.3.1-3) | 0.718 |
今回の題材の結果で見ると、SpinelはRubyよりは速いがC++ほどではなかった。
Looking at the results for this particular problem, Spinel was faster than plain Ruby, but not as fast as C++.
上記C++はO3でビルドした結果で、Spinelはcc(筆者環境ではgcc 14.3.1)をO2で実行するので、念のためC++の方もO2でビルドしてみましたが、速度はほぼ同じでした。
The C++ result above was built with -O3, while Spinel uses cc (GCC 14.3.1 in my environment) with -O2. Just to be safe, I also built the C++ version with -O2, but its execution speed was almost the same.
ということで改めて、今回の題材でSpinelは何をしていたのだろう?
So, let’s take another look at what Spinel was actually doing in this experiment.
Spinelで一気に実行ファイルを作るのではなく、オプションをつけてC言語作成の段階で止めてもらってみます。
Instead of having Spinel generate the executable in one go, I’ll use an option to stop the process after generating the C source code.
spinel myapp.rb -c
すると、
This produces the following output:
Wrote myapp.c
では、最小自由数の核心部分を見てみます。
Now, let’s examine the core part of the Minimum Free Number implementation.
Rubyでは、
In Ruby, we wrote:
us, vs = xs.partition { |x| x < b }
と書いていたところです。
This is the part we’re interested in.
生成されたCには、こんなコードがありました。
The generated C code contains the following:
sp_PolyArray *_t2 = sp_poly_enum_recv(lv_xs, "partition");
SP_GC_ROOT(_t2);
sp_PolyArray * _t3 = _t2;
SP_GC_ROOT(_t3);
sp_PolyArray *_t4 = sp_PolyArray_new();
SP_GC_ROOT(_t4);
sp_PolyArray *_t5 = sp_PolyArray_new();
SP_GC_ROOT(_t5);
for (sp_int _t6 = 0;
_t6 < sp_PolyArray_length(_t3);
_t6++) {
lv_x = sp_PolyArray_get(_t3, _t6);
if (sp_poly_lt(lv_x, sp_box_int(lv_b)))
sp_PolyArray_push(_t4, sp_PolyArray_get(_t3, _t6));
else
sp_PolyArray_push(_t5, sp_PolyArray_get(_t3, _t6));
}
Rubyの
The Ruby expression:
xs.partition { |x| x < b }
が、Cでは
is translated into a C loop:
for (...) {
...
}
になっています。
That’s a for loop in C!
次に、上記「xs.partition」のxsの部分を見ていきます。
Next, let’s look at the xs part of xs.partition.
xsは、最小自由数を見つける問題のための入力データ(正の整数の配列)です。
xs is the input data for the Minimum Free Number problem: an array of positive integers.
myapp.c の minfrom() の引数を見ると、
Looking at the arguments of minfrom() in myapp.c, we find:
static inline sp_int sp_minfrom(
sp_int lv_a,
sp_int lv_n,
sp_RbVal lv_xs
)
となっています。
The function signature looks like this.
a と n は、
The arguments a and n are:
sp_int lv_a
sp_int lv_n
なのに、
But xs is:
xs → sp_RbVal
です。
なんだ sp_RbVal って?
What is sp_RbVal?
Spinelの中身の方を検索していくと以下の定義がありました。
Digging into Spinel’s source code, I found the following definition:
typedef struct {
int tag;
int cls_id;
union {
sp_int i;
const char *s;
sp_float f;
sp_bool b;
void *p;
} v;
} sp_RbVal;
sp_RbVal は、Rubyの動的な型の値を表現するためのCの構造体に見えます。
sp_RbVal appears to be a C structure designed to represent Ruby’s dynamically typed values.
今回の題材では、Rubyの変数「xs」は、minfrom() の引数として受け取られており、生成されたCコードでは sp_RbVal 型として扱われています。
In this example, the Ruby variable xs is passed as an argument to minfrom(). In the generated C code, it is treated as type sp_RbVal.
一方、実験として同じ [43308,43319,...] という整数配列を定数として定義しただけのRubyからSpinelでCを生成したときは、型が sp_IntArray となっていました。
On the other hand, when I generated C code with Spinel from a Ruby program that simply defined the same integer array [43308,43319,...] as a constant, its type was sp_IntArray.
なぜ同じ整数配列なのに表現が違うのかはわかっておりませんが、今回は関数の引数として渡された xs をコンパイル時に sp_IntArray と言い切ることができなかったため、sp_RbVal 型として扱われたのだと認識しています。
I don’t yet know why the same integer array is represented differently. My current understanding is that, in this case, Spinel could not determine at compile time that xs, passed as a function argument, was definitely an sp_IntArray. Therefore, it was treated as an sp_RbVal.
そして今注目している処理「xs.partition { |x| x < b }」の x < b は、
Now, let’s look at the x < b part of the expression xs.partition { |x| x < b }.
sp_poly_lt(lv_x, sp_box_int(lv_b))
となっています。
It becomes the expression above.
b は sp_int として扱われていますが、比較するときには sp_box_int() で sp_RbVal に変換され、sp_RbVal 型の lv_x に揃えられている様に見えます。
b is treated as an sp_int, but when performing the comparison, it appears to be converted into an sp_RbVal using sp_box_int(), so that it matches the type of lv_x.
さらに sp_poly_lt() の中では、sp_RbVal の tag などを lv_x と lv_b の比較に使っているのかも知れないです。
Furthermore, inside sp_poly_lt(), the tag field and other information in sp_RbVal may be used to compare lv_x and lv_b.
つまり、ここまで追いかけて見えてきたことは
So, here’s what I’ve discovered so far:
Ruby
↓
Spinel
↓
Rubyの動的な(実行時まで型を決めない)値を
Cのstruct + union + tagで表現
↓
Cコード生成
↓
GCC
↓
ネイティブバイナリ
Ruby
↓
Spinel
↓
Represent Ruby’s dynamically typed values
(values whose types are not fixed until runtime)
using C structs + unions + tags
↓
Generate C code
↓
GCC
↓
Native binary
SpinelはRubyの動的型付けを捨ててCの静的型付けに無理やり押し込んでいるのではなく、Rubyの動的な値を扱う仕組みそのものをCで実装している。
Spinel doesn’t discard Ruby’s dynamic typing and forcibly squeeze everything into C’s static type system. Instead, it implements the mechanisms for handling Ruby’s dynamic values directly in C.
これはすごいと思いました。
I thought that was amazing.
いやまだ全然わかっちゃいないんだけど。
Well, I still don’t really understand how it all works yet.
そして、ここでC++版のコードを思い出します。
And now, I’m reminded of the C++ version.
C++版では、
In the C++ version, we have:
int x;
int b;
if (x < b) {
...
}
です。
That’s it.
一方Spinelでは、
With Spinel, on the other hand:
sp_RbVal x;
sp_int b;
sp_poly_lt(x, sp_box_int(b));
となっています。
It looks like this.
この違いを見ると、
Looking at this difference, we can see that:
「SpinelはRubyをCにしているが、C++の int のように値の型を単純な整数だけに絞り込んでいるわけではない。必要に応じて sp_RbVal で動的な型として値を表現している」
“Spinel compiles Ruby into C, but it doesn’t restrict values to simple integers like C++’s int. Instead, it uses sp_RbVal to represent dynamically typed values when necessary.”
ということが読み取れます。
That’s what I can infer from the generated code.
今回、
In this experiment, the results were:
Ruby 18.103 ms
Spinel 3.684 ms
C++ 0.718 ms
となった理由を考えると、このあたりも関係していそうです。
When thinking about why we got these results, this difference may be one of the contributing factors.
ただし、ここで「intじゃなくてsp_RbValだから遅い」と断定するのはまだ早いです。
However, it’s too early to conclude that “it’s slower because it uses sp_RbVal instead of int.”
sp_PolyArray_get()
sp_PolyArray_push()
sp_poly_lt()
などが実際に何をしているのか。
We still need to investigate what these functions actually do.
ここまで掘ると、もう少し具体的に「SpinelがどんなCを生成して、どこでコストが発生しているのか」が見えてきそうです。
Digging deeper into these functions should help us understand more concretely what kind of C code Spinel generates and where the performance costs arise.
……が、今回は一旦ここまでとします。
…but I’ll leave it here for now.
現時点の感想 / My Thoughts So Far
Spinelすげえ!
Spinel is amazing!
Matzすげえ!
Matz is amazing!
追記1 : Spinel版の処理時間計測にFFIでC言語を使っていることについて / Addendum1 : Using C via FFI to Measure Execution Time in the Spinel Version
今回、実行時間の計測をRubyではbenchmarkライブラリを使って行なっています。
In the Ruby version, I use the benchmark library to measure execution time.
Spinel版でも当初はRubyのbenchmarkライブラリを使おうとしたのですが、Spinelではコンパイルエラーとなり利用できませんでした。そこで、FFI経由でCのclock()を呼び出して計測することにしました。
I initially tried to use Ruby’s benchmark library in the Spinel version as well, but it resulted in a compilation error and could not be used. So I measured execution time by calling C’s clock() function through FFI.
最初は「まだ開発初期だから、対応していないライブラリもあるのだろう」くらいに考えていました。
At first, I thought, “Spinel is still in its early stages of development, so there are probably some libraries it doesn’t support yet.”
しかし、日経ソフトウェア2026年9月号の、まつもとゆきひろさんによるSpinelの記事を読み直して、少し見方が変わりました。
However, after rereading Matz’s article about Spinel in the September 2026 issue of Nikkei Software, my perspective changed a little.
記事では、Rubyの動的な性質をすべてそのままC言語に変換するのではなく、実際のRubyプログラムはそこまで動的ではないという観察に基づき、ある種の制限を加えたRubyのサブセットをAOTコンパイルする、という考え方が紹介されています。
The article describes an approach in which, rather than translating all of Ruby’s dynamic features directly into C, Spinel AOT-compiles a subset of Ruby with certain restrictions, based on the observation that real-world Ruby programs are not necessarily that dynamic.
今回のbenchmarkが使えなかった理由が、この設計思想によるものなのか、単に未実装なのかは分かりません。
I don’t know whether benchmark was unavailable in this case because of this design philosophy or simply because it has not been implemented yet.
ただ、SpinelはCRubyそのものを再現することを目指しているのではなく、Rubyのプログラムを効率的なネイティブコードにするため、コンパイルできる範囲を定めているのだと考えると、今回の経験もSpinelの特徴を知る一つのきっかけになりました。
Still, if we think of Spinel not as aiming to reproduce CRuby itself, but as defining a range of Ruby programs that can be compiled into efficient native code, then this experience has also become an opportunity to learn more about Spinel’s characteristics.
追記2 : SpinelがC++より遅い主因が見えた。SpinelはRubyをそのままCにしている! / Addendum2 : I Found a Major Reason Why Spinel Is Slower Than C++
ここで、なぜ今回の最小自由数の問題でC++の方がSpinelより速かったのか、もう少し調べてみました。
At this point, I wanted to investigate a little further why C++ was faster than Spinel in this particular Minimum Free Number problem.
今回のC++版が速かった要因の一つが、std::partition だったことを思い出しました。
I remembered that one of the factors contributing to the speed of the C++ version was std::partition.
C++の std::partition は、入力範囲そのものを破壊的に変更して、条件を満たす要素と満たさない要素を分けます。
C++'s std::partition destructively rearranges the elements in the input range, separating the elements that satisfy the condition from those that do not.
一方、今回のRubyでは、
On the other hand, the Ruby version uses:
us, vs = xs.partition { |x| x < b }
Rubyの Array#partition は、入力配列 xs を変更せず、条件を満たす要素を us、満たさない要素を vs という新しい配列に分けて返します。
Ruby's Array#partition does not modify the input array xs. Instead, it creates new arrays containing the elements that satisfy and do not satisfy the condition, returning them as us and vs.
そして、SpinelがこのRubyコードから生成したCコードを確認してみました。
So I checked the C code generated by Spinel from this Ruby code.
すると……
And there it was…
ちゃんと配列を作っていました。
It was actually creating new arrays.
生成されたCコードには、以下の処理がありました。
The generated C code contains the following:
lv__y2_yes = sp_PolyArray_new();
lv__y2_no = sp_PolyArray_new();
for (sp_int _t6 = 0;
_t6 < sp_poly_arr_len_ex(lv__y2___self);
_t6++) {
lv__y2_x = sp_poly_each_elem(lv__y2___self, _t6);
sp_PolyArray_push(
((condition) ? lv__y2_yes : lv__y2_no),
lv__y2_x
);
}
つまり、
In other words:
Ruby
xs.partition { |x| x < b }
↓ Spinel
C
新しい配列を2つ作る
↓
xsの各要素を走査する
↓
条件によってどちらかにpushする
Ruby
xs.partition { |x| x < b }
↓ Spinel
C
Create two new arrays
↓
Iterate over every element of xs
↓
Push each element into one of the two arrays
さらに、この2つの配列をまとめるための配列まで作っています。
It even creates another array to hold these two resulting arrays.
sp_PolyArray *_t7 = sp_PolyArray_new();
sp_PolyArray_push(_t7, ...lv__y2_yes...);
sp_PolyArray_push(_t7, ...lv__y2_no...);
なるほど。
Aha.
だからC++より遅いのか。
So that's why it's slower than C++.
C++版では std::partition が入力配列を直接変更しているのに対して、Spinel版ではRubyの Array#partition の仕様どおり、新しい配列を作っています。
In the C++ version, std::partition modifies the input range directly, while the Spinel version creates new arrays, just as Ruby's Array#partition specifies.
最初は、
At first, I was thinking:
「C++の方が速い。SpinelはまだC++ほど最適化されていないのかな?」
“C++ is faster. Maybe Spinel just isn't optimized as well as C++ yet?”
と思っていました。
That was my initial thought.
でも、生成されたCコードを見てみると、Spinelは勝手にRubyの処理を別のアルゴリズムに置き換えていない。
But looking at the generated C code, Spinel isn't arbitrarily replacing Ruby's behavior with a different algorithm.
Rubyの partition が「入力を変更せず、新しい配列を返す」という仕様なら、生成されたCでもちゃんと新しい配列を作っている。
If Ruby's partition means “do not modify the input and return new arrays,” then the generated C actually creates those new arrays.
つまり、
In other words:
SpinelはRubyを勝手に改造していない。
Spinel isn't secretly modifying Ruby.
Rubyの意味をちゃんと保ったまま、Cにしている。
It is translating Ruby into C while preserving its semantics.
SpinelはC++より遅い
Spinel is slower than C++
というより、
今回のC++版は、Ruby版とは異なる破壊的な処理をしていた
The C++ version used a more destructive operation than the Ruby version
と考えた方が、今回の結果を正確に表している気がします。
That seems to describe the result more accurately.
Spinelは勝手に「こっちの方が速いから」という理由でRubyの処理を書き換えたりせず、Rubyの仕様に従って、必要ならちゃんと配列を作っていました。
It doesn't simply rewrite Ruby's behavior because a different implementation would be faster. It follows Ruby's semantics and creates arrays when that is what Ruby requires.
やっぱすげえぜSpinel!
Spinel is seriously impressive!