diff --git a/benchmark/v8/heap-profile-stop.js b/benchmark/v8/heap-profile-stop.js new file mode 100644 index 000000000000..f5c2592d5557 --- /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 b55c7c46b692..85342ed76d56 100644 --- a/src/env.cc +++ b/src/env.cc @@ -2646,8 +2646,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"); @@ -2655,7 +2655,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 e75556578522..6d220b4c8588 100644 --- a/src/json_utils.h +++ b/src/json_utils.h @@ -5,7 +5,7 @@ #include "node_concepts.h" -#include +#include #include #include #include @@ -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 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 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 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 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 inline void write_value(T number) { - if constexpr (std::is_same::value) - out_ << (number ? "true" : "false"); - else - out_ << number; + if constexpr (std::is_same_v) { + write(number ? "true" : "false"); + } else if constexpr (std::is_same_v || + std::is_same_v || + std::is_same_v) { + write(static_cast(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) { + 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 bc595ebdbbd4..07757d39217c 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 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 1176eb8952db..08f40ee04f6b 100644 --- a/src/node_profiling.h +++ b/src/node_profiling.h @@ -7,7 +7,7 @@ #include "v8.h" #include -#include +#include namespace node { @@ -21,7 +21,7 @@ struct HeapProfileOptions { HeapProfileOptions ParseHeapProfileOptions( const v8::FunctionCallbackInfo& 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 df916deae98f..9758826ae8b3 100644 --- a/src/node_v8.cc +++ b/src/node_v8.cc @@ -331,12 +331,12 @@ void StartHeapProfile(const FunctionCallbackInfo& args) { void StopHeapProfile(const FunctionCallbackInfo& 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 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 9c8f215e094e..c767f9ff52db 100644 --- a/src/node_worker.cc +++ b/src/node_worker.cc @@ -1122,15 +1122,14 @@ void Worker::StopHeapProfile(const FunctionCallbackInfo& 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& args) { }; if (success) { Local 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 3d5a78921170..868f0c8b260e 100644 --- a/test/cctest/test_json_utils.cc +++ b/test/cctest/test_json_utils.cc @@ -2,6 +2,10 @@ #include "gtest/gtest.h" +#include +#include +#include + 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::min()); + writer.json_element(std::numeric_limits::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::max()); + writer.json_element(std::numeric_limits::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); +}