Skip to content

likely/unlikely unlikely to implement unless unless is unlikely but how likely is that? #11910

@didactic-drunk

Description

@didactic-drunk

Instead of adding likely/unlikely as keywords, reuse unless to indicate unlikely. This is likely to speed things up (See by the numbers below)

Why? Many types of conditionals are clearly less likely. Some examples:

def foo(str, size)
  # Guard conditions
  raise "empty str" unless str && str.presence
  raise "invalid size" unless size >= MINIMUM

  # c extension return values
  r = Libc.system_call
  raise Errno... unless r >= 0

  # Any other unlikely boolean
  cache_data unless Dir.exists?("cache_dir")

  ...
end

IAQ (Imaginary asked questions)

  1. Would this break anything? No
  2. Will this slow anything down? unlikely
  3. Sorry, I missed that? I'll say it slower: stall stall stall unlikely

By the numbers

My understanding is if/unless are assumed to be true, however code is not necessarily written to take advantage of this making branch mispredictions normal.

There are ~350 if and 64 unless statements in crystal. 9 of the unless statements raise which I assume are guard conditions.
The first 10 unless entries, all except one appear to be unlikely conditions. It appears unless is already used for unlikely conditions. If anything this PR will improve existing code rather than slowing it down.

Providing unlikely via unless developers have the option to provide optimized conditionals for their existing if statements.

Other

First covered in #1712 and #5661.

Bonus points: Make the compiler parse the title without a cache miss.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions