DEV Community

loading...
Okinawa Ruby User Group

Optimize boot time of ruby CLI tools

Seiei Miyagi
こんにちは
・1 min read

Create a binstub like following:

#!/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 takes two arguments, 1st is name of gem, 2nd is name of executable. You can modify gem_name/exe_name to apply this binstub to other ruby CLI tools.

Without this binstub:

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

With this binstub, It takes a little more time at first run:

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

But once it runs, the cache is created. Then It becomes much faster:

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

You don't need to change any code of ruby CLI tools, Just create a binstub to optimize boot time.

Cheers <3


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

Discussion (0)