function LoopObservable() {
const listeners = new Set();
this.on = fn => listeners.add(fn);
this.off = fn => listeners.delete(fn);
this.clear = () => listeners.clear();
// This has bad failure modes.
this.send = function(message) {
for (let fn of listeners)
fn(message);
};
};
function EventTargetObservable() {
// Name is arbitrary because we're using a dedicated object. Use a shorter
// name for shorter lookup.
const NAME = '.';
const __ = document.createTextNode(null);
this.on = function(handler) {
__.addEventListener(NAME, event => {
handler(event.detail);
});
};
this.off = function(handler) {
__.removeEventListener(NAME, handler);
};
this.send = function(detail) {
__.dispatchEvent(new CustomEvent(NAME, {detail}));
};
}
function run_test(observable, handlers = 2, calls = 1000) {
for (let i = 0; i < handlers; i++)
observable.on(message => console.log(i, message));
for (let i = 0; i < calls; i++)
observable.send({type: "hello", i});
}
run_test(new LoopObservable());
run_test(new EventTargetObservable());
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
loop observable | |
EventTarget observable |
Test name | Executions per second |
---|---|
loop observable | 740.4 Ops/sec |
EventTarget observable | 476.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
The provided benchmark definition json represents two test cases: "loop observable" and "EventTarget observable". These tests compare the performance of implementing the "observable" pattern in JavaScript using two different approaches:
EventTarget
interface in JavaScript to dispatch events. An event target object is created, and listeners are added using the addEventListener
method. When a message is sent, an event is dispatched with the message as its detail property.Options compared:
Pros and cons of each approach:
Library:
The EventTargetObservable
implementation uses a custom EventTarget
class, which is a dedicated object for dispatching events. The addEventListener
method is used to attach listeners, and dispatchEvent
is used to send an event with a message.
Special JS feature or syntax:
This benchmark does not use any special JavaScript features or syntax beyond the standard language definition.
Other alternatives:
In addition to the two approaches mentioned above, other alternatives for implementing observables in JavaScript include:
While these alternatives offer different trade-offs, they can be useful in specific scenarios or when working with complex use cases.
In summary, the "loop observable" and "EventTarget observable" benchmarks on MeasureThat.net compare two approaches for implementing the "observable" pattern in JavaScript. The loop over callbacks approach is simple but may lead to silent failures, while the EventTarget approach provides better failure modes but requires additional setup.