LoginSignup
11
3

More than 5 years have passed since last update.

rubyで大きな配列をハッシュに変換する時のスタックの枯渇に注意

Posted at

fiberを使ったrubyプログラムでfiberに割り当てられたスタック領域を使い切ってプロセスが死ぬという問題が起こりました。

落ちた原因を調査していると、以下のようなコードが原因であることが分かりました。

big_array = [[:hoge 'fuga'], [:foo, 'bar'], ...] # 巨大な配列
Hash[*big_array.flatten]

Hash.[]に引数として渡している配列が大きすぎるために、スタックを使い切ってしまっていたようです。

こちらの資料によると、スタックサイズは数十〜数百KBなので、それ以上のサイズの配列を引数に渡すとスタックが枯渇します。
http://www.atdot.net/~ko1/diary/edit_comment.cgi?mode=edit&year=2012&month=12&day=21

ruby 2.1以降ではArray#to_hが実装されているので、そちらを使いましょう。

11
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
3