perf: optimize GenerateRandomString() #66
Loading…
Reference in a new issue
No description provided.
Delete branch "perf-generate-random-string"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
The previous implementation used an
std::stringstream
to concatenate the generated random string.The new one uses a simple preallocated
std::string
, as the size of the output is already known - it is thelength
parameter.It also uses
std::generate_n()
instead of an explicit loop, making the code more concise and potentially faster, as no calls tostd::string::operator+=
are needed.Calling
GenerateRandomString(1'000'000)
with thestd::stringstream
-based implementation allocated 16 times, for a total of 3'173'516 bytes. The new one cuts this down to 4 allocs, for a total of 1'076'864 bytes.Inspired by #64
This can be made even more efficient with two simple changes. The first is to use .resize here
And replace this with
result[i] = characters[index_dist(gen)];
That lets you avoid the overhead that comes with appending (size tracking and checks)
I've changed this to std::generate_n(), so that no loop is needed at all.
Done
thanks!
Just curious, how does
.resize()
improve things compared to.reserve()
?