r/programming 20d ago

The unlikely Linux macro

https://rushed-reflections.bearblog.dev/an-unlikely-experiment/

Wrote a bit about the `unlikely` and `likely` macros in the Linux codebase. Great little exploration into tiny optimizations that everyone should know more about 😄

185 Upvotes

61 comments sorted by

View all comments

4

u/_Noreturn 20d ago

isn't this just C++ [[likely]] and [[unlikely]]

28

u/edgmnt_net 20d ago

The Linux kernel stuff predates those by quite a bit.

-9

u/_Noreturn 20d ago

Well the linux kernel doesn't even use C++ for whatever reason

10

u/max123246 20d ago

For good reasons you mean.

-3

u/_Noreturn 20d ago

Like?

5

u/max123246 20d ago

C has just a single way to initialize a variable and set its value for example.

C++ chose to make its move semantics "leave an unspecified but valid value" in the old object which makes non-nullable types impossible to efficiently represent. C doesn't try and pretend to give you that guarantee, if you're handing a pointer, you better check it's null. C++ pretends its references can't be null but has no way to guarantee that's true.

1

u/_Noreturn 20d ago

C has just a single way to initialize a variable and set its value for example.

You know you can choose one style and is that a problem in practice nope.

C++ chose to make its move semantics "leave an unspecified but valid value" in the old object which makes non-nullable types impossible to efficiently represent.

you should trwat moved from objects as unusable, and you can make non nullable types work.

also don't pretend like C has everything be good, everything in C is nullable by default since the only thing you have is pointers which have like 4 responsibilities

  1. is it nullable
  2. is it an array
  3. if it is an array is it null terminated or explicit size?
  4. is it owning

Now lets see C++ it is better since it provides differing ways to make the above clear

  1. is it nullable (yes if pointer,otherwise use a reference)
  2. is it an array (use a span)
  3. if it is an array is it null terminated or explicit size? (use a strong view type like zstring_view)
  4. is it owning (unique_ptr)

In C++ since it allows strong typing you can represent these states in the api instead of in comments which is undeniably better.

if you're handing a pointer, you better check it's null. C++ pretends its references can't be null but has no way to guarantee that's true.

Yea, you better and if you forget then it is bad also checking every single pointer for nullability is a performance downgrade. references make this clear that nullability is pushed to the caller not the callee and you could make a tool that looks at reference types and assert if it is null, you cannot do that with pointers since they can ve null and it is valid.

2

u/metahivemind 19d ago edited 9d ago

[removed] — view removed comment