Skip to content

Commit dabbbee

Browse files
IlyasShabiaduh95
authored andcommitted
src: speed up heap profile serialization
Signed-off-by: ishabi <ilyasshabi94@gmail.com> PR-URL: #67685 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent 34ee914 commit dabbbee

8 files changed

Lines changed: 166 additions & 48 deletions

File tree

‎benchmark/v8/heap-profile-stop.js‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'use strict';
2+
3+
const common = require('../common.js');
4+
const assert = require('node:assert');
5+
const { startHeapProfile } = require('node:v8');
6+
7+
const bench = common.createBenchmark(main, {
8+
n: [1e4, 1e5],
9+
}, {
10+
test: { n: 1e3 },
11+
});
12+
13+
function main({ n }) {
14+
const handle = startHeapProfile({ sampleInterval: 64 });
15+
// Keep the sampled allocations alive until after stop().
16+
const retained = globalThis.retained = new Array(n);
17+
for (let i = 0; i < n; i++) {
18+
retained[i] = new Array(16).fill(i);
19+
}
20+
21+
bench.start();
22+
const profile = handle.stop();
23+
bench.end(1);
24+
25+
assert.ok(JSON.parse(profile).samples.length > 0);
26+
globalThis.retained = undefined;
27+
}

‎src/env.cc‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2673,16 +2673,15 @@ size_t Environment::HeapProfileNearHeapLimitCallback(
26732673

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

2676-
std::ostringstream out;
2677-
if (!node::SerializeHeapProfile(env->isolate(), out)) {
2676+
std::string profile;
2677+
if (!node::SerializeHeapProfile(env->isolate(), profile)) {
26782678
Debug(env,
26792679
DebugCategory::DIAGNOSTICS,
26802680
"No sampling heap profile active; uninstalling callback.\n");
26812681
uninstall_callback();
26822682
return new_limit;
26832683
}
26842684

2685-
std::string profile = std::move(out).str();
26862685
uv_buf_t buffer = uv_buf_init(profile.data(), profile.size());
26872686
const int err = WriteFileSync(filename.c_str(), buffer);
26882687
if (err != 0) {

‎src/json_utils.h‎

Lines changed: 68 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
#include "node_concepts.h"
77

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

3233
private:
34+
inline void write(char ch) {
35+
if (string_out_ != nullptr)
36+
*string_out_ += ch;
37+
else
38+
*out_ << ch;
39+
}
40+
inline void write(std::string_view str) {
41+
if (string_out_ != nullptr)
42+
string_out_->append(str);
43+
else
44+
*out_ << str;
45+
}
3346
inline void indent() { indent_ += 2; }
3447
inline void deindent() { indent_ -= 2; }
3548
inline void advance() {
3649
if (compact_) return;
37-
for (int i = 0; i < indent_; i++) out_ << ' ';
50+
for (int i = 0; i < indent_; i++) write(' ');
3851
}
3952
inline void write_one_space() {
4053
if (compact_) return;
41-
out_ << ' ';
54+
write(' ');
4255
}
4356
inline void write_new_line() {
4457
if (compact_) return;
45-
out_ << '\n';
58+
write('\n');
4659
}
4760

4861
public:
4962
inline void json_start() {
50-
if (state_ == kAfterValue) out_ << ',';
63+
if (state_ == kAfterValue) write(',');
5164
write_new_line();
5265
advance();
53-
out_ << '{';
66+
write('{');
5467
indent();
5568
state_ = kObjectStart;
5669
}
@@ -59,42 +72,42 @@ class JSONWriter {
5972
write_new_line();
6073
deindent();
6174
advance();
62-
out_ << '}';
75+
write('}');
6376
state_ = kAfterValue;
6477
}
6578
template <typename T>
6679
inline void json_objectstart(T key) {
67-
if (state_ == kAfterValue) out_ << ',';
80+
if (state_ == kAfterValue) write(',');
6881
write_new_line();
6982
advance();
7083
write_string(key);
71-
out_ << ':';
84+
write(':');
7285
write_one_space();
73-
out_ << '{';
86+
write('{');
7487
indent();
7588
state_ = kObjectStart;
7689
}
7790

7891
template <typename T>
7992
inline void json_arraystart(T key) {
80-
if (state_ == kAfterValue) out_ << ',';
93+
if (state_ == kAfterValue) write(',');
8194
write_new_line();
8295
advance();
8396
write_string(key);
84-
out_ << ':';
97+
write(':');
8598
write_one_space();
86-
out_ << '[';
99+
write('[');
87100
indent();
88101
state_ = kObjectStart;
89102
}
90103
inline void json_objectend() {
91104
write_new_line();
92105
deindent();
93106
advance();
94-
out_ << '}';
107+
write('}');
95108
if (indent_ == 0) {
96109
// Top-level object is complete, so end the line.
97-
out_ << '\n';
110+
write('\n');
98111
}
99112
state_ = kAfterValue;
100113
}
@@ -103,24 +116,24 @@ class JSONWriter {
103116
write_new_line();
104117
deindent();
105118
advance();
106-
out_ << ']';
119+
write(']');
107120
state_ = kAfterValue;
108121
}
109122
template <typename T, typename U>
110123
inline void json_keyvalue(const T& key, const U& value) {
111-
if (state_ == kAfterValue) out_ << ',';
124+
if (state_ == kAfterValue) write(',');
112125
write_new_line();
113126
advance();
114127
write_string(key);
115-
out_ << ':';
128+
write(':');
116129
write_one_space();
117130
write_value(value);
118131
state_ = kAfterValue;
119132
}
120133

121134
template <typename U>
122135
inline void json_element(const U& value) {
123-
if (state_ == kAfterValue) out_ << ',';
136+
if (state_ == kAfterValue) write(',');
124137
write_new_line();
125138
advance();
126139
write_value(value);
@@ -136,30 +149,53 @@ class JSONWriter {
136149
private:
137150
template <NumericValue T>
138151
inline void write_value(T number) {
139-
if constexpr (std::is_same<T, bool>::value)
140-
out_ << (number ? "true" : "false");
141-
else
142-
out_ << number;
152+
if constexpr (std::is_same_v<T, bool>) {
153+
write(number ? "true" : "false");
154+
} else if constexpr (std::is_same_v<T, char> ||
155+
std::is_same_v<T, signed char> ||
156+
std::is_same_v<T, unsigned char>) {
157+
write(static_cast<char>(number));
158+
} else {
159+
if (out_ != nullptr) {
160+
*out_ << number;
161+
return;
162+
}
163+
// Enough for any integer, or a floating-point value with six digits
164+
// and an exponent. Match the default ostream precision.
165+
char buffer[128];
166+
std::to_chars_result result;
167+
if constexpr (std::is_floating_point_v<T>) {
168+
result = std::to_chars(buffer,
169+
buffer + sizeof(buffer),
170+
number,
171+
std::chars_format::general,
172+
6);
173+
} else {
174+
result = std::to_chars(buffer, buffer + sizeof(buffer), number);
175+
}
176+
string_out_->append(buffer, result.ptr);
177+
}
143178
}
144179

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

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

152187
inline void write_string(std::string_view str) {
153-
out_ << '"';
188+
write('"');
154189
if (NeedsJsonEscape(str)) // only create temporary std::string if necessary
155-
out_ << EscapeJsonChars(str);
190+
write(EscapeJsonChars(str));
156191
else
157-
out_ << str;
158-
out_ << '"';
192+
write(str);
193+
write('"');
159194
}
160195

161196
enum JSONState { kObjectStart, kAfterValue };
162-
std::ostream& out_;
197+
std::ostream* out_ = nullptr;
198+
std::string* string_out_ = nullptr;
163199
bool compact_;
164200
int indent_ = 0;
165201
int state_ = kObjectStart;

‎src/node_profiling.cc‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,14 @@ static void BuildHeapProfileNode(Isolate* isolate,
4545
writer->json_arrayend();
4646
}
4747

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

5858
writer.json_arraystart("samples");

‎src/node_profiling.h‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
#include "v8.h"
88

99
#include <cstdint>
10-
#include <sstream>
10+
#include <string>
1111

1212
namespace node {
1313

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

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

2626
struct CpuProfileOptions {
2727
int sampling_interval_us = 0;

‎src/node_v8.cc‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -331,12 +331,12 @@ void StartHeapProfile(const FunctionCallbackInfo<Value>& args) {
331331
void StopHeapProfile(const FunctionCallbackInfo<Value>& args) {
332332
Environment* env = Environment::GetCurrent(args);
333333
Isolate* isolate = env->isolate();
334-
std::ostringstream out_stream;
335-
bool success = node::SerializeHeapProfile(isolate, out_stream);
334+
std::string profile;
335+
bool success = node::SerializeHeapProfile(isolate, profile);
336336
if (success) {
337337
isolate->GetHeapProfiler()->StopSamplingHeapProfiler();
338338
Local<Value> result;
339-
if (ToV8Value(env->context(), out_stream.str(), isolate).ToLocal(&result)) {
339+
if (ToV8Value(env->context(), profile, isolate).ToLocal(&result)) {
340340
args.GetReturnValue().Set(result);
341341
}
342342
} else {

‎src/node_worker.cc‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1122,15 +1122,14 @@ void Worker::StopHeapProfile(const FunctionCallbackInfo<Value>& args) {
11221122

11231123
bool scheduled = w->RequestInterrupt([taker = std::move(taker),
11241124
env](Environment* worker_env) mutable {
1125-
std::ostringstream out_stream;
1126-
bool success =
1127-
node::SerializeHeapProfile(worker_env->isolate(), out_stream);
1125+
std::string profile;
1126+
bool success = node::SerializeHeapProfile(worker_env->isolate(), profile);
11281127
if (success) {
11291128
worker_env->isolate()->GetHeapProfiler()->StopSamplingHeapProfiler();
11301129
}
11311130
env->SetImmediateThreadsafe(
11321131
[taker = std::move(taker),
1133-
out_stream = std::move(out_stream),
1132+
profile = std::move(profile),
11341133
success = success](Environment* env) mutable {
11351134
Isolate* isolate = env->isolate();
11361135
HandleScope handle_scope(isolate);
@@ -1142,8 +1141,7 @@ void Worker::StopHeapProfile(const FunctionCallbackInfo<Value>& args) {
11421141
};
11431142
if (success) {
11441143
Local<Value> result;
1145-
if (!ToV8Value(env->context(), out_stream.str(), isolate)
1146-
.ToLocal(&result)) {
1144+
if (!ToV8Value(env->context(), profile, isolate).ToLocal(&result)) {
11471145
return;
11481146
}
11491147
argv[1] = result;

0 commit comments

Comments
 (0)