14
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby製CLIツールの起動時間を最適化する

Last updated at Posted at 2019-05-29

以下のようなbinstubを作りましょう。

#!/usr/bin/env ruby
require 'bootsnap'
gem_name = 'rubocop'
exe_name = 'rubocop'
cache_dir = File.join(ENV['HOME'], '.cache', 'bootsnap', gem_name, exe_name)
Bootsnap.setup(cache_dir: cache_dir, load_path_cache: false, autoload_paths_cache: false)
load Gem.bin_path(gem_name, exe_name)

Gem.bin_path1は2つ引数を取ります。1つ目がgemの名前で2つ目が実行ファイルの名前です。
gem_name/exe_nameを編集するとrubocop以外の他のCLIツールにもこのbinstubを適用できます。

このbinstubなしの場合

% time rubocop -v
0.70.0
rubocop -v  0.76s user 0.20s system 97% cpu 0.983 total

このbinstubありの場合、初回は多少多めに時間がかかる

% time bin/rubocop -v
0.70.0
bin/rubocop -v  1.04s user 0.57s system 98% cpu 1.640 total

しかし一度実行してしまえばキャッシュが作られてるので早くなる

% time bin/rubocop -v
0.70.0
bin/rubocop -v  0.53s user 0.23s system 79% cpu 0.969 total

CLIツールのソースコードを一切変更せずbinstubつくるだけで起動時間を最適化できます。

やったね ✌('ω'✌ )三✌('ω')✌三( ✌'ω')✌

  1. https://www.rubydoc.info/github/rubygems/rubygems/Gem.bin_path

14
5
1

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
14
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?