Ruby 大家有没有留意过 Kernel::require 这个 API 的性能问题

kowalskidark · May 20, 2021 · Last by kowalskidark replied at May 22, 2021 · 677 hits

完整的 benchmark 代码在 ruby-require-perf

                        user     system      total        real
require(relative)   0.001705   0.003376   0.005081 (  0.005089)
require(absolute)   0.001190   0.000009   0.001199 (  0.001195)
require_relative    0.002576   0.000000   0.002576 (  0.002567)

Kernel::require 在传入一个相对路径的时候比绝对路径要慢了差不多 4 ~5 倍,比 Kernel::require_relative 慢了 2 倍

想知道平时大家在写代码的时候有留意过这个问题吗?

另外这个 Kernel::require API 性能优化的提案在今年的 GSoC Ruby 立项了,也许我们最后能在 ko1 的帮助下调查出来结果

只影响第一次加载?

影响 Ruby 启动,尤其是作为 Cli 工具的场景。比如 Rubocop

Ruby 当 CLI 工具用每次都要手动禁用掉 standard library,否则光 standard library 加上启动就要差几秒。

rails c 会不会慢?

应该是需要调用 Dir 之类的转为普通 require,syscall 多了

Reply to pynix

syscall 只多了一条 getcwd,在 user space 花的时间多了很多

You need to Sign in before reply, if you don't have an account, please Sign up first.