r/cpp • • Feb 16 '26

Favorite optimizations ??

I'd love to hear stories about people's best feats of optimization, or something small you are able to use often!

135 Upvotes

185 comments sorted by

View all comments

Show parent comment

1

u/Big_Target_1405 Feb 16 '26 edited Feb 17 '26

Yeah, that's most of them. But there's still one more optimisation where you need the writer to be as fast as possible and you don't care so much about the reader:

That's letting the reader overrun the writer, such that it doesn't need to read the writers position at all.

This requires that there be a natural null or unset state for your data element (or you need a header) that can be set atomically....the reader can then clear after it reads such that the writer always writes to empty cells. If the reader then overruns on the next spin it will then see a null value it previously placed and return

The writers position then doesn't have to be atomic/shared

This addresses the best case where the reader is essentially riding the writers back and the queue has 1 element in it. This is a tough case because on the next poll the readers cache of the writers position becomes ineffective and the access touches a cache line that's potentially being touched by a later, completely unrelated, write. The writer might not even be writing the element to be read next. The writer could now be several messages ahead, so disrupting that cache line is truly just wasted traffic and hence jitter. You only want to disturb the writer when the reader is literally trying to read the slot the writer is currently writing.

1

u/CocktailPerson Feb 17 '26

My favorite version of this a "broadcast" or "multicast" queue, where the writer is actually allowed to lap readers that fall too far behind. It's only useful if your readers can recover from losing some data in the queue (or don't care about it), but it does mean that the writer never has to wait for a reader, and it means there can be an arbitrary number of readers attached to the queue.

1

u/Big_Target_1405 Feb 17 '26

Yeah it's cool, but I haven't found a use for one in the real world yet ;(