Skip to content

Commit

Permalink
events: use bitset to save memory
Browse files Browse the repository at this point in the history
PR-URL: #43700
Reviewed-By: Gerhard Stöbich <deb2001-github@yahoo.de>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
mabaasit authored and juanarbol committed Oct 10, 2022
1 parent f16f7e3 commit 1bcfe42
Showing 1 changed file with 46 additions and 6 deletions.
52 changes: 46 additions & 6 deletions lib/internal/event_target.js
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,13 @@ function weakListeners() {
return { registry: weakListenersState, map: objectToWeakListenerMap };
}

const kFlagOnce = 1 << 0;
const kFlagCapture = 1 << 1;
const kFlagPassive = 1 << 2;
const kFlagNodeStyle = 1 << 3;
const kFlagWeak = 1 << 4;
const kFlagRemoved = 1 << 5;

// The listeners for an EventTarget are maintained as a linked list.
// Unfortunately, the way EventTarget is defined, listeners are accounted
// using the tuple [handler,capture], and even if we don't actually make
Expand All @@ -409,13 +416,21 @@ class Listener {
previous.next = this;
this.previous = previous;
this.listener = listener;
// TODO(benjamingr) these 4 can be 'flags' to save 3 slots
this.once = once;
this.capture = capture;
this.passive = passive;
this.isNodeStyleListener = isNodeStyleListener;

let flags = 0b0;
if (once)
flags |= kFlagOnce;
if (capture)
flags |= kFlagCapture;
if (passive)
flags |= kFlagPassive;
if (isNodeStyleListener)
flags |= kFlagNodeStyle;
if (weak)
flags |= kFlagWeak;
this.flags = flags;

this.removed = false;
this.weak = Boolean(weak); // Don't retain the object

if (this.weak) {
this.callback = new SafeWeakRef(listener);
Expand All @@ -435,6 +450,31 @@ class Listener {
}
}

get once() {
return Boolean(this.flags & kFlagOnce);
}
get capture() {
return Boolean(this.flags & kFlagCapture);
}
get passive() {
return Boolean(this.flags & kFlagPassive);
}
get isNodeStyleListener() {
return Boolean(this.flags & kFlagNodeStyle);
}
get weak() {
return Boolean(this.flags & kFlagWeak);
}
get removed() {
return Boolean(this.flags & kFlagRemoved);
}
set removed(value) {
if (value)
this.flags |= kFlagRemoved;
else
this.flags &= ~kFlagRemoved;
}

same(listener, capture) {
const myListener = this.weak ? this.listener.deref() : this.listener;
return myListener === listener && this.capture === capture;
Expand Down

0 comments on commit 1bcfe42

Please sign in to comment.