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>
This commit is contained in:
Ilyas Shabi authored and Antoine du Hamel committed 2026-11-24 18:20:02 +01:00
1 parent 34ee914a08
commit dabbbee0fb
8 files changed
+166 -48

No files matched your search

+27
View File
@@ -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;
}
+2 -3
View File
@@ -2673,8 +2673,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");
@@ -2682,7 +2682,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) {
+68 -32
View File
@@ -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;
+2 -2
View File
@@ -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");
+2 -2
View File
@@ -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;
+3 -3
View File
@@ -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 {
+4 -6
View File
@@ -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;
+58
View File
@@ -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);
}