r/cpp • u/PhilipTrettner • Apr 14 '26
How Much Linear Memory Access Is Enough? (A Benchmark)
https://solidean.com/blog/2026/how-much-linear-memory-access-is-enough/I've tried to find a answer to how much contiguous memory you need to run into dimishing returns. Aka if you need to split your work into chunks, how large should the chunks be to capture most of the performance.
It depends a bit on what kind of task and how linear you use the data and if you have other per-block overheads. But at least for my use cases, I was kind of surprised to see that I probably won't need more than ~128 kB. And I wager that more than 1 or 2 MB is enough for everyone based on the results in the post.
NOTE: the experimental setup tries to ensure we're not measuring cache effects (or in a very controlled manner at least). I explicitly tried to make the results provide a userful upper bound via careful setup.
12
u/Old_Vehicle_9147 Apr 14 '26
I see you say you took cache effects into account however the large rises on the graphs do seem to coincide with cache sizes
2
u/Rabbitical Apr 14 '26
It's always good to see real data, and good job on this analysis.
However I would raise one thing: having your blocks accessed by a linear array of pointers is pretty much the ideal scenario for what you would want to do if you had to make what otherwise could be contiguous memory non-contiguous for...some reason. However in the real world I'd argue the main reason you would segment memory like this is because the access pattern is non trivial, which is where the real challenge/potential costs lie. And the reason generally I might increase block size beyond 1MB as the real world cost to access that needs amortizing is usually much, much higher than just a pointer hop. For instance, a hash based caching system that might have to deal with concurrency, or worse, someone managing these memory blocks as individual objects.
Again this is not to say that your study is wrong or not valuable, just that what you're measuring is essentially "break up contiguous memory for the sake of adding an additional step periodically" which feels a bit contrived to me. I can't envision many scenarios where the lookup part of this in an actual program would be so trivial. If all the block indices were meant to be iterated over linearly then there would be no need to contrive such a structure.
Still, of course, it's good to measure at least the minimal access cost like this!
2
u/Stevo15025 Apr 14 '26
Very cool! It would also be cool to try strided access to give you better prefetch behavior. Matt Stuchlik has a really nice article about this.
https://blog.mattstuchlik.com/2024/07/21/fastest-memory-read.html