Project

General

Profile

Actions

Feature #11769

closed

optimize case / when for `nil`

Added by tenderlovemaking (Aaron Patterson) over 8 years ago. Updated over 8 years ago.

Status:
Closed
Target version:
-
[ruby-core:71818]

Description

Hi,

I've noticed that when there are certain values in a case / when statement it gets optimized to a hash lookup. For example, code like this:

def foo socket
  case str = socket.read_nonblock(10, exception: false)
  when :wait_readable
    # do something
  else
    str
  end
end

puts RubyVM::InstructionSequence.of(method(:foo)).disasm

The above code will use opt_case_dispatch instruction with a hash. However, if I use nil in the case statement like this:

def foo socket
  case str = socket.read_nonblock(10, exception: false)
  when :wait_readable
    # do something
  when nil
    # got an EOF
  else
    str
  end
end

puts RubyVM::InstructionSequence.of(method(:foo)).disasm

Then the optimization is lost.

I've attached a patch that adds nil to the optimized case such that the above code will use opt_case_dispatch. My patch defines === on nil, then adds nil to the list of "optimizable literals".


Files

0001-optimize-case-when-for-nil.patch (3.4 KB) 0001-optimize-case-when-for-nil.patch tenderlovemaking (Aaron Patterson), 12/03/2015 09:42 PM
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0