Skip to content

Commit

Permalink
[ruby/irb] Optimize show_source command further
Browse files Browse the repository at this point in the history
ruby/irb#249 actually slowed down how `code` is
concatenated. The original way of creating `code` is faster.

[before]
    user     system      total        real
2.420137   0.005364   2.425501 (  2.426264)

[after]
    user     system      total        real
1.000221   0.007454   1.007675 (  1.008295)

Theoretically, this implementation might skip lines that don't appear in
Ripper tokens, but this assumes such lines don't impact whether the code
passes compilation or not. At least normal blank lines seem to have an
`on_ignored_nl` token anyway though.

ruby/irb@27dd2867cd
  • Loading branch information
k0kubun authored and matzbot committed Jun 27, 2021
1 parent 6eb7c66 commit 35c7e83
Showing 1 changed file with 4 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/irb/cmd/show_source.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,15 @@ def find_end(file, first_line)
lex = RubyLex.new
lines = File.read(file).lines[(first_line - 1)..-1]
tokens = RubyLex.ripper_lex_without_warning(lines.join)

code = +""
prev_tokens = []

# chunk with line number
tokens.chunk { |tok| tok[0][0] }.each do |lnum, chunk|
code = lines[0..lnum].join
code << lines[lnum]
prev_tokens.concat chunk

continue = lex.process_continue(prev_tokens)
code_block_open = lex.check_code_block(code, prev_tokens)
if !continue && !code_block_open
Expand Down

0 comments on commit 35c7e83

Please sign in to comment.