From fe3f472a7613a04831096abffb8ea39c7eeaf4a6 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 3 Dec 2024 19:00:05 +0100 Subject: [PATCH] GeoJSON writing: optimize speed of json_double_with_precision() --- ogr/ogrlibjsonutils.cpp | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/ogr/ogrlibjsonutils.cpp b/ogr/ogrlibjsonutils.cpp index 610d48cf04cb..c41bed974530 100644 --- a/ogr/ogrlibjsonutils.cpp +++ b/ogr/ogrlibjsonutils.cpp @@ -7,6 +7,7 @@ #include "ogrlibjsonutils.h" #include "cpl_string.h" +#include "ogr_geometry.h" #include "ogr_p.h" #include @@ -132,22 +133,28 @@ static int OGR_json_double_with_precision_to_string(struct json_object *jso, json_object_get_userdata(jso); #endif // Precision is stored as a uintptr_t content casted to void* - const uintptr_t nPrecision = reinterpret_cast(userData); - char szBuffer[75] = {}; + const uintptr_t nPrecisionIn = reinterpret_cast(userData); const double dfVal = json_object_get_double(jso); if (fabs(dfVal) > 1e50 && !std::isinf(dfVal)) { + char szBuffer[75] = {}; CPLsnprintf(szBuffer, sizeof(szBuffer), "%.17g", dfVal); + return printbuf_memappend(pb, szBuffer, + static_cast(strlen(szBuffer))); } else { const bool bPrecisionIsNegative = - (nPrecision >> (8 * sizeof(nPrecision) - 1)) != 0; - OGRFormatDouble(szBuffer, sizeof(szBuffer), dfVal, '.', - bPrecisionIsNegative ? 15 - : static_cast(nPrecision)); + (nPrecisionIn >> (8 * sizeof(nPrecisionIn) - 1)) != 0; + const int nPrecision = + bPrecisionIsNegative ? 15 : static_cast(nPrecisionIn); + OGRWktOptions opts(nPrecision, /* round = */ true); + opts.format = OGRWktFormat::F; + + std::string s = OGRFormatDouble(dfVal, opts, 1); + + return printbuf_memappend(pb, s.data(), static_cast(s.size())); } - return printbuf_memappend(pb, szBuffer, static_cast(strlen(szBuffer))); } /************************************************************************/