Commit e7db48902e5 for nodejs

commit e7db48902e56568e5d61767d746a655e72861c8f
Author: Ilyas Shabi <ilyasshabi94@gmail.com>
Date:   Tue Nov 24 10:18:59 2026 +0100

    src: speed up heap profile serialization

    Signed-off-by: ishabi <ilyasshabi94@gmail.com>
    PR-URL: https://github.com/nodejs/node/pull/67685
    Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
    Reviewed-By: James M Snell <jasnell@gmail.com>

diff --git a/benchmark/v8/heap-profile-stop.js b/benchmark/v8/heap-profile-stop.js
new file mode 100644
index 00000000000..f5c2592d555
--- /dev/null
+++ b/benchmark/v8/heap-profile-stop.js
@@ -0,0 +1,27 @@
+'use strict';
+
+const common = require('../common.js');
+const assert = require('node:assert');
+const { startHeapProfile } = require('node:v8');
+
+const bench = common.createBenchmark(main, {
+  n: [1e4, 1e5],
+}, {
+  test: { n: 1e3 },
+});
+
+function main({ n }) {
+  const handle = startHeapProfile({ sampleInterval: 64 });
+  // Keep the sampled allocations alive until after stop().
+  const retained = globalThis.retained = new Array(n);
+  for (let i = 0; i < n; i++) {
+    retained[i] = new Array(16).fill(i);
+  }
+
+  bench.start();
+  const profile = handle.stop();
+  bench.end(1);
+
+  assert.ok(JSON.parse(profile).samples.length > 0);
+  globalThis.retained = undefined;
+}
diff --git a/src/env.cc b/src/env.cc
index be131ad0a52..8dabc275dfd 100644
--- a/src/env.cc
+++ b/src/env.cc
@@ -2671,8 +2671,8 @@ size_t Environment::HeapProfileNearHeapLimitCallback(

   Debug(env, DebugCategory::DIAGNOSTICS, "Writing %s...\n", *name);

-  std::ostringstream out;
-  if (!node::SerializeHeapProfile(env->isolate(), out)) {
+  std::string profile;
+  if (!node::SerializeHeapProfile(env->isolate(), profile)) {
     Debug(env,
           DebugCategory::DIAGNOSTICS,
           "No sampling heap profile active; uninstalling callback.\n");
@@ -2680,7 +2680,6 @@ size_t Environment::HeapProfileNearHeapLimitCallback(
     return new_limit;
   }

-  std::string profile = std::move(out).str();
   uv_buf_t buffer = uv_buf_init(profile.data(), profile.size());
   const int err = WriteFileSync(filename.c_str(), buffer);
   if (err != 0) {
diff --git a/src/json_utils.h b/src/json_utils.h
index e7555657852..6d220b4c858 100644
--- a/src/json_utils.h
+++ b/src/json_utils.h
@@ -5,7 +5,7 @@

 #include "node_concepts.h"

-#include <iomanip>
+#include <charconv>
 #include <limits>
 #include <ostream>
 #include <string>
@@ -26,31 +26,44 @@ std::string Reindent(const std::string& str, int indentation);
 // JSON compiler definitions.
 class JSONWriter {
  public:
-  JSONWriter(std::ostream& out, bool compact)
-    : out_(out), compact_(compact) {}
+  JSONWriter(std::ostream& out, bool compact) : out_(&out), compact_(compact) {}
+  JSONWriter(std::string& out, bool compact)
+      : string_out_(&out), compact_(compact) {}

  private:
+  inline void write(char ch) {
+    if (string_out_ != nullptr)
+      *string_out_ += ch;
+    else
+      *out_ << ch;
+  }
+  inline void write(std::string_view str) {
+    if (string_out_ != nullptr)
+      string_out_->append(str);
+    else
+      *out_ << str;
+  }
   inline void indent() { indent_ += 2; }
   inline void deindent() { indent_ -= 2; }
   inline void advance() {
     if (compact_) return;
-    for (int i = 0; i < indent_; i++) out_ << ' ';
+    for (int i = 0; i < indent_; i++) write(' ');
   }
   inline void write_one_space() {
     if (compact_) return;
-    out_ << ' ';
+    write(' ');
   }
   inline void write_new_line() {
     if (compact_) return;
-    out_ << '\n';
+    write('\n');
   }

  public:
   inline void json_start() {
-    if (state_ == kAfterValue) out_ << ',';
+    if (state_ == kAfterValue) write(',');
     write_new_line();
     advance();
-    out_ << '{';
+    write('{');
     indent();
     state_ = kObjectStart;
   }
@@ -59,31 +72,31 @@ class JSONWriter {
     write_new_line();
     deindent();
     advance();
-    out_ << '}';
+    write('}');
     state_ = kAfterValue;
   }
   template <typename T>
   inline void json_objectstart(T key) {
-    if (state_ == kAfterValue) out_ << ',';
+    if (state_ == kAfterValue) write(',');
     write_new_line();
     advance();
     write_string(key);
-    out_ << ':';
+    write(':');
     write_one_space();
-    out_ << '{';
+    write('{');
     indent();
     state_ = kObjectStart;
   }

   template <typename T>
   inline void json_arraystart(T key) {
-    if (state_ == kAfterValue) out_ << ',';
+    if (state_ == kAfterValue) write(',');
     write_new_line();
     advance();
     write_string(key);
-    out_ << ':';
+    write(':');
     write_one_space();
-    out_ << '[';
+    write('[');
     indent();
     state_ = kObjectStart;
   }
@@ -91,10 +104,10 @@ class JSONWriter {
     write_new_line();
     deindent();
     advance();
-    out_ << '}';
+    write('}');
     if (indent_ == 0) {
       // Top-level object is complete, so end the line.
-      out_ << '\n';
+      write('\n');
     }
     state_ = kAfterValue;
   }
@@ -103,16 +116,16 @@ class JSONWriter {
     write_new_line();
     deindent();
     advance();
-    out_ << ']';
+    write(']');
     state_ = kAfterValue;
   }
   template <typename T, typename U>
   inline void json_keyvalue(const T& key, const U& value) {
-    if (state_ == kAfterValue) out_ << ',';
+    if (state_ == kAfterValue) write(',');
     write_new_line();
     advance();
     write_string(key);
-    out_ << ':';
+    write(':');
     write_one_space();
     write_value(value);
     state_ = kAfterValue;
@@ -120,7 +133,7 @@ class JSONWriter {

   template <typename U>
   inline void json_element(const U& value) {
-    if (state_ == kAfterValue) out_ << ',';
+    if (state_ == kAfterValue) write(',');
     write_new_line();
     advance();
     write_value(value);
@@ -136,30 +149,53 @@ class JSONWriter {
  private:
   template <NumericValue T>
   inline void write_value(T number) {
-    if constexpr (std::is_same<T, bool>::value)
-      out_ << (number ? "true" : "false");
-    else
-      out_ << number;
+    if constexpr (std::is_same_v<T, bool>) {
+      write(number ? "true" : "false");
+    } else if constexpr (std::is_same_v<T, char> ||
+                         std::is_same_v<T, signed char> ||
+                         std::is_same_v<T, unsigned char>) {
+      write(static_cast<char>(number));
+    } else {
+      if (out_ != nullptr) {
+        *out_ << number;
+        return;
+      }
+      // Enough for any integer, or a floating-point value with six digits
+      // and an exponent. Match the default ostream precision.
+      char buffer[128];
+      std::to_chars_result result;
+      if constexpr (std::is_floating_point_v<T>) {
+        result = std::to_chars(buffer,
+                               buffer + sizeof(buffer),
+                               number,
+                               std::chars_format::general,
+                               6);
+      } else {
+        result = std::to_chars(buffer, buffer + sizeof(buffer), number);
+      }
+      string_out_->append(buffer, result.ptr);
+    }
   }

-  inline void write_value(Null null) { out_ << "null"; }
+  inline void write_value(Null null) { write("null"); }
   inline void write_value(std::string_view str) { write_string(str); }

   inline void write_value(const ForeignJSON& json) {
-    out_ << Reindent(json.as_string, indent_);
+    write(Reindent(json.as_string, indent_));
   }

   inline void write_string(std::string_view str) {
-    out_ << '"';
+    write('"');
     if (NeedsJsonEscape(str))  // only create temporary std::string if necessary
-      out_ << EscapeJsonChars(str);
+      write(EscapeJsonChars(str));
     else
-      out_ << str;
-    out_ << '"';
+      write(str);
+    write('"');
   }

   enum JSONState { kObjectStart, kAfterValue };
-  std::ostream& out_;
+  std::ostream* out_ = nullptr;
+  std::string* string_out_ = nullptr;
   bool compact_;
   int indent_ = 0;
   int state_ = kObjectStart;
diff --git a/src/node_profiling.cc b/src/node_profiling.cc
index bc595ebdbbd..07757d39217 100644
--- a/src/node_profiling.cc
+++ b/src/node_profiling.cc
@@ -45,14 +45,14 @@ static void BuildHeapProfileNode(Isolate* isolate,
   writer->json_arrayend();
 }

-bool SerializeHeapProfile(Isolate* isolate, std::ostringstream& out_stream) {
+bool SerializeHeapProfile(Isolate* isolate, std::string& out) {
   HandleScope scope(isolate);
   HeapProfiler* profiler = isolate->GetHeapProfiler();
   std::unique_ptr<AllocationProfile> profile(profiler->GetAllocationProfile());
   if (!profile) {
     return false;
   }
-  JSONWriter writer(out_stream, true);
+  JSONWriter writer(out, true);
   writer.json_start();

   writer.json_arraystart("samples");
diff --git a/src/node_profiling.h b/src/node_profiling.h
index 1176eb8952d..08f40ee04f6 100644
--- a/src/node_profiling.h
+++ b/src/node_profiling.h
@@ -7,7 +7,7 @@
 #include "v8.h"

 #include <cstdint>
-#include <sstream>
+#include <string>

 namespace node {

@@ -21,7 +21,7 @@ struct HeapProfileOptions {
 HeapProfileOptions ParseHeapProfileOptions(
     const v8::FunctionCallbackInfo<v8::Value>& args);

-bool SerializeHeapProfile(v8::Isolate* isolate, std::ostringstream& out_stream);
+bool SerializeHeapProfile(v8::Isolate* isolate, std::string& out);

 struct CpuProfileOptions {
   int sampling_interval_us = 0;
diff --git a/src/node_v8.cc b/src/node_v8.cc
index df916deae98..9758826ae8b 100644
--- a/src/node_v8.cc
+++ b/src/node_v8.cc
@@ -331,12 +331,12 @@ void StartHeapProfile(const FunctionCallbackInfo<Value>& args) {
 void StopHeapProfile(const FunctionCallbackInfo<Value>& args) {
   Environment* env = Environment::GetCurrent(args);
   Isolate* isolate = env->isolate();
-  std::ostringstream out_stream;
-  bool success = node::SerializeHeapProfile(isolate, out_stream);
+  std::string profile;
+  bool success = node::SerializeHeapProfile(isolate, profile);
   if (success) {
     isolate->GetHeapProfiler()->StopSamplingHeapProfiler();
     Local<Value> result;
-    if (ToV8Value(env->context(), out_stream.str(), isolate).ToLocal(&result)) {
+    if (ToV8Value(env->context(), profile, isolate).ToLocal(&result)) {
       args.GetReturnValue().Set(result);
     }
   } else {
diff --git a/src/node_worker.cc b/src/node_worker.cc
index 9c8f215e094..c767f9ff52d 100644
--- a/src/node_worker.cc
+++ b/src/node_worker.cc
@@ -1122,15 +1122,14 @@ void Worker::StopHeapProfile(const FunctionCallbackInfo<Value>& args) {

   bool scheduled = w->RequestInterrupt([taker = std::move(taker),
                                         env](Environment* worker_env) mutable {
-    std::ostringstream out_stream;
-    bool success =
-        node::SerializeHeapProfile(worker_env->isolate(), out_stream);
+    std::string profile;
+    bool success = node::SerializeHeapProfile(worker_env->isolate(), profile);
     if (success) {
       worker_env->isolate()->GetHeapProfiler()->StopSamplingHeapProfiler();
     }
     env->SetImmediateThreadsafe(
         [taker = std::move(taker),
-         out_stream = std::move(out_stream),
+         profile = std::move(profile),
          success = success](Environment* env) mutable {
           Isolate* isolate = env->isolate();
           HandleScope handle_scope(isolate);
@@ -1142,8 +1141,7 @@ void Worker::StopHeapProfile(const FunctionCallbackInfo<Value>& args) {
           };
           if (success) {
             Local<Value> result;
-            if (!ToV8Value(env->context(), out_stream.str(), isolate)
-                     .ToLocal(&result)) {
+            if (!ToV8Value(env->context(), profile, isolate).ToLocal(&result)) {
               return;
             }
             argv[1] = result;
diff --git a/test/cctest/test_json_utils.cc b/test/cctest/test_json_utils.cc
index 3d5a7892117..868f0c8b260 100644
--- a/test/cctest/test_json_utils.cc
+++ b/test/cctest/test_json_utils.cc
@@ -2,6 +2,10 @@

 #include "gtest/gtest.h"

+#include <cstdint>
+#include <limits>
+#include <sstream>
+
 TEST(JSONUtilsTest, EscapeJsonChars) {
   using node::EscapeJsonChars;
   EXPECT_EQ("abc", EscapeJsonChars("abc"));
@@ -24,3 +28,57 @@ TEST(JSONUtilsTest, EscapeJsonChars) {
     EXPECT_EQ("a" + expected[i], EscapeJsonChars("a" + input));
   }
 }
+
+TEST(JSONUtilsTest, StringWriter) {
+  auto write = [](node::JSONWriter* writer) {
+    writer->json_start();
+    writer->json_keyvalue("text", std::string_view("\"\\\n\0", 4));
+    writer->json_keyvalue("utf8", "caf\xc3\xa9");
+    writer->json_arraystart("values");
+    writer->json_element(true);
+    writer->json_element(false);
+    writer->json_element(node::JSONWriter::Null{});
+    writer->json_start();
+    writer->json_objectstart("empty");
+    writer->json_objectend();
+    writer->json_end();
+    writer->json_arrayend();
+    writer->json_objectend();
+  };
+
+  for (bool compact : {false, true}) {
+    std::ostringstream stream;
+    node::JSONWriter stream_writer(stream, compact);
+    write(&stream_writer);
+    std::string output;
+    node::JSONWriter string_writer(output, compact);
+    write(&string_writer);
+    EXPECT_EQ(stream.str(), output);
+    if (compact) {
+      EXPECT_EQ("{\"text\":\"\\\"\\\\\\n\\u0000\",\"utf8\":\"caf\xc3\xa9\","
+                "\"values\":[true,false,null,{\"empty\":{}}]}\n",
+                output);
+    }
+  }
+}
+
+TEST(JSONUtilsTest, StringWriterNumbers) {
+  std::string output;
+  node::JSONWriter writer(output, true);
+  writer.json_start();
+  writer.json_arraystart("numbers");
+  writer.json_element(std::numeric_limits<int64_t>::min());
+  writer.json_element(std::numeric_limits<uint64_t>::max());
+  writer.json_element(0);
+  writer.json_element(-0.0);
+  writer.json_element(1.23456789);
+  writer.json_element(1000000.0);
+  writer.json_element(0.00001);
+  writer.json_element(std::numeric_limits<double>::max());
+  writer.json_element(std::numeric_limits<double>::denorm_min());
+  writer.json_arrayend();
+  writer.json_end();
+  EXPECT_EQ("{\"numbers\":[-9223372036854775808,18446744073709551615,0,-0,"
+            "1.23457,1e+06,1e-05,1.79769e+308,4.94066e-324]}",
+            output);
+}