[demangler] Improve buffer hysteresis

Improve demangler buffer hysteresis.  If we needed more than double
the buffer, the original code would allocate exactly the amount
needed, and thus consequently the next request would also realloc.
We're very unlikely to get into wanting more than double, after the
first allocation, as it would require the user to have used an
identifier larger than the hysteresis.  With machine generated code
that's possible, but unlikely.

Reviewed By: ChuanqiXu

Differential Revision: https://reviews.llvm.org/D119972
This commit is contained in:
Nathan Sidwell 2022-02-16 08:03:24 -08:00
parent e5c98e22fb
commit 024495e626
3 changed files with 21 additions and 8 deletions

View File

@ -37,10 +37,10 @@ class OutputBuffer {
void grow(size_t N) { void grow(size_t N) {
size_t Need = N + CurrentPosition; size_t Need = N + CurrentPosition;
if (Need > BufferCapacity) { if (Need > BufferCapacity) {
// Avoid many reallocations during startup, with a bit of hysteresis. // Reduce the number of reallocations, with a bit of hysteresis. The
constexpr size_t MinInitAlloc = 1024; // number here is chosen so the first allocation will more-than-likely not
if (Need < MinInitAlloc) // allocate more than 1K.
Need = MinInitAlloc; Need += 1024 - 32;
BufferCapacity *= 2; BufferCapacity *= 2;
if (BufferCapacity < Need) if (BufferCapacity < Need)
BufferCapacity = Need; BufferCapacity = Need;

View File

@ -37,10 +37,10 @@ class OutputBuffer {
void grow(size_t N) { void grow(size_t N) {
size_t Need = N + CurrentPosition; size_t Need = N + CurrentPosition;
if (Need > BufferCapacity) { if (Need > BufferCapacity) {
// Avoid many reallocations during startup, with a bit of hysteresis. // Reduce the number of reallocations, with a bit of hysteresis. The
constexpr size_t MinInitAlloc = 1024; // number here is chosen so the first allocation will more-than-likely not
if (Need < MinInitAlloc) // allocate more than 1K.
Need = MinInitAlloc; Need += 1024 - 32;
BufferCapacity *= 2; BufferCapacity *= 2;
if (BufferCapacity < Need) if (BufferCapacity < Need)
BufferCapacity = Need; BufferCapacity = Need;

View File

@ -78,3 +78,16 @@ TEST(OutputBufferTest, Prepend) {
std::free(OB.getBuffer()); std::free(OB.getBuffer());
} }
// Test when initial needed size is larger than the default.
TEST(OutputBufferTest, Extend) {
OutputBuffer OB;
char Massive[2000];
std::memset(Massive, 'a', sizeof(Massive));
Massive[sizeof(Massive) - 1] = 0;
OB << Massive;
EXPECT_EQ(Massive, toString(OB));
std::free(OB.getBuffer());
}