3 ms·
What he meant that if you have an array of strings that implement Small String Optimization AND those strings are short (i.e. below the threshold for Small Stri
by kjksf 5y ago
What he meant that if you have an array of strings that implement Small String Optimization AND those strings are short (i.e. below the threshold for Small String Optimization) THEN they'll be contiguous in memory.
But you can be smarter than that. As it happens, I just implemented "vector of strings" where all strings are contiguous in memory.
The code: https://github.com/sumatrapdfreader/sumatrapdf/commit/bc83112ff0b9607f1155e6b923001f2ea0e0286c#diff-35f8652bb542c1e449b60087a004e5b479a92f3a1f70f748da1fbada6813148eR2704 https://github.com/sumatrapdfreader/sumatrapdf/commit/bc8311...
The basic idea is like you said: you keep strings contiguously in memory and maintain a separate array of pointers to each string. Except it's not a pointer but u32 index into that block of memory.
Even if those were pointers, not the u32 indexes, it would still be cache friendly.
The point is that strings are close together.
If each string was allocated with malloc() then you don't control where they are allocated.
In the worst case each string could end up in a separate cache line, which would be much slower if you were to iterate over all strings.