From 9c29c8ddfcfb8b413c004240fda95bb56c7d106c Mon Sep 17 00:00:00 2001 From: Tim Wojtulewicz Date: Wed, 11 Aug 2021 15:40:09 -0700 Subject: [PATCH] GH-1713: Avoid unneeded reallocs in SerializationFormat::WriteData --- src/SerializationFormat.cc | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/SerializationFormat.cc b/src/SerializationFormat.cc index ad9e2b26d9..fe5d34bbe2 100644 --- a/src/SerializationFormat.cc +++ b/src/SerializationFormat.cc @@ -82,10 +82,18 @@ bool SerializationFormat::ReadData(void* b, size_t count) bool SerializationFormat::WriteData(const void* b, size_t count) { // Increase buffer if necessary. + bool size_changed = false; while ( output_pos + count > output_size ) + { output_size *= GROWTH_FACTOR; + size_changed = true; + } - output = (char*)util::safe_realloc(output, output_size); + // The glibc standard states explicitly that calling realloc with the same + // size is a no-op, but the same claim can't be made on other platforms. + // There's really no reason to do that though. + if ( size_changed ) + output = (char*)util::safe_realloc(output, output_size); memcpy(output + output_pos, b, count); output_pos += count;