-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Description
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)
- Would this break anything? No
- Will this slow anything down?
unlikely
- 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.