Skip to content

Commit e413350

Browse files
committed
timers: cross JS/C++ border less frequently
This removes the `process._needImmediateCallback` property and its semantics of having a 1/0 switch that tells C++ whether immediates are currently scheduled. Instead, a counter keeping track of all immediates is created, that can be increased on `setImmediate()` or decreased when an immediate is run or cleared. This is faster, because rather than reading/writing a C++ getter, this operation can be performed as a direct memory read/write via a typed array. The only C++ call that is left to make is activating the native handles upon creation of the first `Immediate` after the queue is empty. One other (good!) side-effect is that `immediate._destroyed` now reliably tells whether an `immediate` is still scheduled to run or not. Also, as a nice extra, this should make it easier to implement an internal variant of `setImmediate` for C++ that piggybacks off the same mechanism, which should be useful at least for async hooks and HTTP/2. Benchmark results: $ ./node benchmark/compare.js --new ./node --old ./node-master-1b093cb93df0 --runs 10 --filter immediate timers | Rscript benchmark/compare.R [00:08:53|% 100| 4/4 files | 20/20 runs | 1/1 configs]: Done improvement confidence p.value timers/immediate.js type="breadth" thousands=2000 25.61 % ** 1.432301e-03 timers/immediate.js type="breadth1" thousands=2000 7.66 % 1.320233e-01 timers/immediate.js type="breadth4" thousands=2000 4.61 % 5.669053e-01 timers/immediate.js type="clear" thousands=2000 311.40 % *** 3.896291e-07 timers/immediate.js type="depth" thousands=2000 17.54 % ** 9.755389e-03 timers/immediate.js type="depth1" thousands=2000 17.09 % *** 7.176229e-04 timers/set-immediate-breadth-args.js millions=5 10.63 % * 4.250034e-02 timers/set-immediate-breadth.js millions=10 20.62 % *** 9.150439e-07 timers/set-immediate-depth-args.js millions=10 17.97 % *** 6.819135e-10 PR-URL: nodejs#17064
1 parent f52c2b9 commit e413350

File tree

4 files changed

+69
-73
lines changed

4 files changed

+69
-73
lines changed

lib/timers.js

+24-22
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,13 @@ const { kInit, kDestroy, kAsyncIdCounter } = async_wrap.constants;
4646
const async_id_symbol = Symbol('asyncId');
4747
const trigger_async_id_symbol = Symbol('triggerAsyncId');
4848

49+
/* This is an Uint32Array for easier sharing with C++ land. */
50+
const scheduledImmediateCount = process._scheduledImmediateCount;
51+
delete process._scheduledImmediateCount;
52+
/* Kick off setImmediate processing */
53+
const activateImmediateCheck = process._activateImmediateCheck;
54+
delete process._activateImmediateCheck;
55+
4956
// Timeout values > TIMEOUT_MAX are set to 1.
5057
const TIMEOUT_MAX = 2147483647; // 2^31-1
5158

@@ -731,15 +738,9 @@ function processImmediate() {
731738
else
732739
immediate = next;
733740
}
734-
735-
// Only round-trip to C++ land if we have to. Calling clearImmediate() on an
736-
// immediate that's in |queue| is okay. Worst case is we make a superfluous
737-
// call to NeedImmediateCallbackSetter().
738-
if (!immediateQueue.head) {
739-
process._needImmediateCallback = false;
740-
}
741741
}
742742

743+
process._immediateCallback = processImmediate;
743744

744745
// An optimization so that the try/finally only de-optimizes (since at least v8
745746
// 4.7) what is in this smaller function.
@@ -751,13 +752,17 @@ function tryOnImmediate(immediate, oldTail) {
751752
runCallback(immediate);
752753
threw = false;
753754
} finally {
754-
// clearImmediate checks _callback === null for kDestroy hooks.
755755
immediate._callback = null;
756756
if (!threw)
757757
emitAfter(immediate[async_id_symbol]);
758-
if (async_hook_fields[kDestroy] > 0 && !immediate._destroyed) {
759-
emitDestroy(immediate[async_id_symbol]);
758+
759+
if (!immediate._destroyed) {
760760
immediate._destroyed = true;
761+
scheduledImmediateCount[0]--;
762+
763+
if (async_hook_fields[kDestroy] > 0) {
764+
emitDestroy(immediate[async_id_symbol]);
765+
}
761766
}
762767

763768
if (threw && immediate._idleNext) {
@@ -860,10 +865,9 @@ function createImmediate(args, callback) {
860865
immediate._argv = args;
861866
immediate._onImmediate = callback;
862867

863-
if (!process._needImmediateCallback) {
864-
process._needImmediateCallback = true;
865-
process._immediateCallback = processImmediate;
866-
}
868+
if (scheduledImmediateCount[0] === 0)
869+
activateImmediateCheck();
870+
scheduledImmediateCount[0]++;
867871

868872
immediateQueue.append(immediate);
869873

@@ -874,18 +878,16 @@ function createImmediate(args, callback) {
874878
exports.clearImmediate = function(immediate) {
875879
if (!immediate) return;
876880

877-
if (async_hook_fields[kDestroy] > 0 &&
878-
immediate._callback !== null &&
879-
!immediate._destroyed) {
880-
emitDestroy(immediate[async_id_symbol]);
881+
if (!immediate._destroyed) {
882+
scheduledImmediateCount[0]--;
881883
immediate._destroyed = true;
884+
885+
if (async_hook_fields[kDestroy] > 0) {
886+
emitDestroy(immediate[async_id_symbol]);
887+
}
882888
}
883889

884890
immediate._onImmediate = null;
885891

886892
immediateQueue.remove(immediate);
887-
888-
if (!immediateQueue.head) {
889-
process._needImmediateCallback = false;
890-
}
891893
};

src/env-inl.h

+6
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,7 @@ inline Environment::Environment(IsolateData* isolate_data,
304304
abort_on_uncaught_exception_(false),
305305
emit_napi_warning_(true),
306306
makecallback_cntr_(0),
307+
scheduled_immediate_count_(isolate_, 1),
307308
#if HAVE_INSPECTOR
308309
inspector_agent_(new inspector::Agent(this)),
309310
#endif
@@ -533,6 +534,11 @@ inline void Environment::set_fs_stats_field_array(double* fields) {
533534
fs_stats_field_array_ = fields;
534535
}
535536

537+
inline AliasedBuffer<uint32_t, v8::Uint32Array>&
538+
Environment::scheduled_immediate_count() {
539+
return scheduled_immediate_count_;
540+
}
541+
536542
inline performance::performance_state* Environment::performance_state() {
537543
return performance_state_;
538544
}

src/env.h

+4
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,8 @@ class Environment {
618618
inline double* fs_stats_field_array() const;
619619
inline void set_fs_stats_field_array(double* fields);
620620

621+
inline AliasedBuffer<uint32_t, v8::Uint32Array>& scheduled_immediate_count();
622+
621623
inline performance::performance_state* performance_state();
622624
inline std::map<std::string, uint64_t>* performance_marks();
623625

@@ -714,6 +716,8 @@ class Environment {
714716
size_t makecallback_cntr_;
715717
std::vector<double> destroy_async_id_list_;
716718

719+
AliasedBuffer<uint32_t, v8::Uint32Array> scheduled_immediate_count_;
720+
717721
performance::performance_state* performance_state_ = nullptr;
718722
std::map<std::string, uint64_t> performance_marks_;
719723

src/node.cc

+35-51
Original file line numberDiff line numberDiff line change
@@ -371,25 +371,6 @@ static void PrintErrorString(const char* format, ...) {
371371
}
372372

373373

374-
static void CheckImmediate(uv_check_t* handle) {
375-
Environment* env = Environment::from_immediate_check_handle(handle);
376-
HandleScope scope(env->isolate());
377-
Context::Scope context_scope(env->context());
378-
MakeCallback(env->isolate(),
379-
env->process_object(),
380-
env->immediate_callback_string(),
381-
0,
382-
nullptr,
383-
{0, 0}).ToLocalChecked();
384-
}
385-
386-
387-
static void IdleImmediateDummy(uv_idle_t* handle) {
388-
// Do nothing. Only for maintaining event loop.
389-
// TODO(bnoordhuis) Maybe make libuv accept nullptr idle callbacks.
390-
}
391-
392-
393374
static inline const char *errno_string(int errorno) {
394375
#define ERRNO_CASE(e) case e: return #e;
395376
switch (errorno) {
@@ -3262,39 +3243,40 @@ static void DebugEnd(const FunctionCallbackInfo<Value>& args);
32623243

32633244
namespace {
32643245

3265-
void NeedImmediateCallbackGetter(Local<Name> property,
3266-
const PropertyCallbackInfo<Value>& info) {
3267-
Environment* env = Environment::GetCurrent(info);
3268-
const uv_check_t* immediate_check_handle = env->immediate_check_handle();
3269-
bool active = uv_is_active(
3270-
reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
3271-
info.GetReturnValue().Set(active);
3246+
bool MaybeStopImmediate(Environment* env) {
3247+
if (env->scheduled_immediate_count()[0] == 0) {
3248+
uv_check_stop(env->immediate_check_handle());
3249+
uv_idle_stop(env->immediate_idle_handle());
3250+
return true;
3251+
}
3252+
return false;
32723253
}
32733254

3255+
void CheckImmediate(uv_check_t* handle) {
3256+
Environment* env = Environment::from_immediate_check_handle(handle);
3257+
HandleScope scope(env->isolate());
3258+
Context::Scope context_scope(env->context());
32743259

3275-
void NeedImmediateCallbackSetter(
3276-
Local<Name> property,
3277-
Local<Value> value,
3278-
const PropertyCallbackInfo<void>& info) {
3279-
Environment* env = Environment::GetCurrent(info);
3260+
if (MaybeStopImmediate(env))
3261+
return;
32803262

3281-
uv_check_t* immediate_check_handle = env->immediate_check_handle();
3282-
bool active = uv_is_active(
3283-
reinterpret_cast<const uv_handle_t*>(immediate_check_handle));
3263+
MakeCallback(env->isolate(),
3264+
env->process_object(),
3265+
env->immediate_callback_string(),
3266+
0,
3267+
nullptr,
3268+
{0, 0}).ToLocalChecked();
32843269

3285-
if (active == value->BooleanValue())
3286-
return;
3270+
MaybeStopImmediate(env);
3271+
}
32873272

3288-
uv_idle_t* immediate_idle_handle = env->immediate_idle_handle();
32893273

3290-
if (active) {
3291-
uv_check_stop(immediate_check_handle);
3292-
uv_idle_stop(immediate_idle_handle);
3293-
} else {
3294-
uv_check_start(immediate_check_handle, CheckImmediate);
3295-
// Idle handle is needed only to stop the event loop from blocking in poll.
3296-
uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
3297-
}
3274+
void ActivateImmediateCheck(const FunctionCallbackInfo<Value>& args) {
3275+
Environment* env = Environment::GetCurrent(args);
3276+
uv_check_start(env->immediate_check_handle(), CheckImmediate);
3277+
// Idle handle is needed only to stop the event loop from blocking in poll.
3278+
uv_idle_start(env->immediate_idle_handle(),
3279+
[](uv_idle_t*){ /* do nothing, just keep the loop running */ });
32983280
}
32993281

33003282

@@ -3517,12 +3499,11 @@ void SetupProcessObject(Environment* env,
35173499
Integer::New(env->isolate(), GetProcessId()));
35183500
READONLY_PROPERTY(process, "features", GetFeatures(env));
35193501

3520-
auto need_immediate_callback_string =
3521-
FIXED_ONE_BYTE_STRING(env->isolate(), "_needImmediateCallback");
3522-
CHECK(process->SetAccessor(env->context(), need_immediate_callback_string,
3523-
NeedImmediateCallbackGetter,
3524-
NeedImmediateCallbackSetter,
3525-
env->as_external()).FromJust());
3502+
auto scheduled_immediate_count =
3503+
FIXED_ONE_BYTE_STRING(env->isolate(), "_scheduledImmediateCount");
3504+
CHECK(process->Set(env->context(),
3505+
scheduled_immediate_count,
3506+
env->scheduled_immediate_count().GetJSArray()).FromJust());
35263507

35273508
// -e, --eval
35283509
if (eval_string) {
@@ -3648,6 +3629,9 @@ void SetupProcessObject(Environment* env,
36483629
env->as_external()).FromJust());
36493630

36503631
// define various internal methods
3632+
env->SetMethod(process,
3633+
"_activateImmediateCheck",
3634+
ActivateImmediateCheck);
36513635
env->SetMethod(process,
36523636
"_startProfilerIdleNotifier",
36533637
StartProfilerIdleNotifier);

0 commit comments

Comments
 (0)