r/cpp • u/Little-Reflection986 • 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
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.