Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
custom events vs pubSub custom
(version: 0)
Comparing performance of:
pubSub vs custom event
Created:
2 years ago
by:
Guest
Jump to the latest result
Tests:
pubSub
class PubSub { constructor() { // Keep track of all `onMessage()` listeners with easy lookup by subscription id. this.subscriberOnMsg = {}; // Keep track of the topic for each subscription id for easier cleanup. this.subscriberTopics = {}; // Keep track of all topics and subscriber ids for each topic. this.topics = {}; } /** * Subscribe to messages being published in the given topic. * @param {string} topic - Name of the channel/topic where messages are published. * @param {Function} onMessage - Function called whenever new messages on the topic are published. * @returns {string} ID of this subscription. */ subscribe(topic, onMessage) { // Validate inputs if (typeof topic !== "string") throw new Error("Topic must be a string."); if (typeof onMessage !== "function") throw new Error("onMessage must be a function."); // Each subscription has a unique id const subID = Date.now(); // Create or Update the topic if (!(topic in this.topics)) { // New topic this.topics[topic] = [subID]; } else { // Topic exists this.topics[topic].push(subID); } // Store onMessage and topic separately for faster lookup this.subscriberOnMsg[subID] = onMessage; this.subscriberTopics[subID] = topic; // Return the subscription id return subID; } /** * Publish messages on a topic for all subscribers to receive. * @param {string} topic - The topic where the message is sent. * @param {Object} message - The message to send. Only object format is supported. */ publish(topic, message) { if (typeof topic !== "string") throw new Error("Topic must be a string."); if (typeof message !== "object") { throw new Error("Message must be an object."); } // If topic exists, post messages if (topic in this.topics) { const subIDs = this.topics[topic]; subIDs.forEach((id) => { if (id in this.subscriberOnMsg) { this.subscriberOnMsg[id](message); } }); } } /** * Unsubscribe for a given subscription id. * @param {string} id - Subscription id */ unsubscribe(id) { // Validate inputs if (typeof id !== "string" || !validateUUID(id)) { throw new Error("ID must be a valid UUID."); } // If the id exists in our subscriptions then clear it. if (id in this.subscriberOnMsg && id in this.subscriberTopics) { // Delete message listener delete this.subscriberOnMsg[id]; // Remove id from the topics tracker const topic = this.subscriberTopics[id]; // Cleanup topics if (topic && topic in this.topics) { const idx = this.topics[topic].findIndex((tID) => tID === id); if (idx > -1) { this.topics[topic].splice(idx, 1); } // If there are no more listeners, clean up the topic as well if (this.topics[topic].length === 0) { delete this.topics[topic]; } } // Delete the topic for this id delete this.subscriberTopics[id]; } } } // Example usage: const results = []; const PS = new PubSub(); const subId = PS.subscribe("myTopic", (message) => { console.log({ message }); results.push(message); }); PS.publish("myTopic", { message: "Hello World" }); let i = 10000; while (--i) { PS.publish("myTopic", { message: "Hello World" }); }
custom event
class PubSub { constructor() { // Create a DOM element to serve as the event bus this.eventBus = document.createElement("div"); } /** * Subscribe to events with a given topic. * @param {string} topic - The topic to subscribe to. * @param {Function} callback - The callback function to execute when the event is published. * @returns {Function} - A function to unsubscribe from the topic. */ subscribe(topic, callback) { // Create a unique event type for the topic const eventType = `pubsub_${topic}`; // Define the event handler function const eventHandler = (event) => { callback(event.detail); }; // Add the event handler to the event bus this.eventBus.addEventListener(eventType, eventHandler); // Return an unsubscribe function return () => { this.eventBus.removeEventListener(eventType, eventHandler); }; } /** * Publish an event with a given topic and data. * @param {string} topic - The topic of the event. * @param {any} data - The data to send with the event. */ publish(topic, data) { // Create a unique event type for the topic const eventType = `pubsub_${topic}`; // Create a custom event with the data const customEvent = new CustomEvent(eventType, { detail: data, }); // Dispatch the custom event on the event bus this.eventBus.dispatchEvent(customEvent); } } // Example usage: const PS = new PubSub(); const results = []; // Subscribe to an event PS.subscribe("myTopic", (message) => { console.log({ message }); results.push(message); }); let i = 10000; while (--i) { PS.publish("myTopic", { message: "Hello World" }); }
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (2)
Previous results
Fork
Test case name
Result
pubSub
custom event
Fastest:
N/A
Slowest:
N/A
Latest run results:
No previous run results
This benchmark does not have any results yet. Be the first one
to run it!
Autogenerated LLM Summary
(model
llama3.2:3b
, generated one year ago):
I'll provide an answer based on the provided benchmark results. The latest benchmark result shows two tests: `pubSub` and `custom event`. The test `pubSub` has a high execution rate of 30.17963981628418 executions per second, indicating that it is relatively fast. In contrast, the test `custom event` has a lower execution rate of 19.48579216003418 executions per second. Based on this information, I would say that the `pubSub` test is likely faster than the `custom event` test. However, without more context or details about what these tests are measuring (e.g., performance, scalability, latency), it's difficult to provide a definitive conclusion. If you'd like, I can try to provide some general insights on what might be causing the difference in execution rates between these two tests, but please keep in mind that this would be speculative without more information.
Related benchmarks:
momentjs isBefore versus lt operator
Moment valueOf vs. new Date().getTime()
Date.now() vs Moment()
MomentJS vs Native test
MomentJS vs Native Date
Comments
Confirm delete:
Do you really want to delete benchmark?