From da1768c35479df3cf99bdfa8c0577589393a2cca Mon Sep 17 00:00:00 2001 From: Augustin Cavalier Date: Thu, 9 Apr 2026 14:26:24 -0400 Subject: [PATCH] StringForSize: Preinitialize the BNumberFormats. I noticed when profiling the system with ActivityMonitor running that most of ActivityMonitor's time was spent initializing these for the Memory view. So, instead, cache the formatters to avoid needing to reinitialize them so often. --- src/kits/shared/StringForSize.cpp | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/kits/shared/StringForSize.cpp b/src/kits/shared/StringForSize.cpp index b471416781..d6901e15af 100644 --- a/src/kits/shared/StringForSize.cpp +++ b/src/kits/shared/StringForSize.cpp @@ -21,10 +21,25 @@ using BPrivate::gSystemCatalog; #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "StringForSize" +static BNumberFormat* sNumberFormat0; +static BNumberFormat* sNumberFormat2; +static pthread_once_t sNumberFormatInit = PTHREAD_ONCE_INIT; + namespace BPrivate { +static void +InitializeNumberFormats() +{ + sNumberFormat0 = new BNumberFormat; + sNumberFormat0->SetPrecision(0); + + sNumberFormat2 = new BNumberFormat; + sNumberFormat2->SetPrecision(2); +} + + const char* string_for_size(double size, char* string, size_t stringSize) { @@ -47,10 +62,13 @@ string_for_size(double size, char* string, size_t stringSize) gSystemCatalog.GetString(kFormats[index], B_TRANSLATION_CONTEXT, "size unit")); formatter.Format(format, size); + // Initializing and changing the parameters of BNumberFormats is expensive, + // so we cache the two we need globally. + pthread_once(&sNumberFormatInit, InitializeNumberFormats); + BString printedSize; - BNumberFormat numberFormat; - numberFormat.SetPrecision(index == 0 ? 0 : 2); - numberFormat.Format(printedSize, size); + BNumberFormat* numberFormat = (index == 0) ? sNumberFormat0 : sNumberFormat2; + numberFormat->Format(printedSize, size); snprintf(string, stringSize, format.String(), printedSize.String());