Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
custom events vs pubSub custom with map and set
(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 subscribers using a Map this.subscribers = new Map(); // Keep track of all topics using a Set this.topics = new Set(); } /** * 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."); // Generate a unique subscription ID const subID = Date.now().toString(); // Add the subscriber to the set of subscribers for the topic if (!this.subscribers.has(topic)) { this.subscribers.set(topic, new Map()); } this.subscribers.get(topic).set(subID, onMessage); // Add the topic to the set of topics this.topics.add(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) { // Validate inputs 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 to subscribers if (this.subscribers.has(topic)) { const subscribers = this.subscribers.get(topic); for (const [subID, onMessage] of subscribers.entries()) { onMessage(message); } } } /** * Unsubscribe for a given subscription id. * @param {string} id - Subscription id */ unsubscribe(id) { // Iterate through topics and remove the subscriber for (const topic of this.topics) { const subscribers = this.subscribers.get(topic); if (subscribers && subscribers.has(id)) { subscribers.delete(id); if (subscribers.size === 0) { this.subscribers.delete(topic); this.topics.delete(topic); } return; } } } }
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):
Let's break down the benchmark and explain what is being tested. **Benchmark Overview** The benchmark tests three different approaches for publishing events: `pubSub`, `customEvent`, and another implementation of `pubSub`. The test measures the performance difference between these approaches, specifically in terms of the number of executions per second. **`pubSub` Approach** The `pubSub` approach uses a Pub-Sub (Publish-Subscribe) pattern to publish events. In this implementation: * A `PubSub` class is defined with a constructor that initializes an event bus (a DOM element). * The `subscribe` method allows subscribers to register their callback functions for specific topics. * The `publish` method publishes events on the topic, triggering the registered callbacks. **Pros of `pubSub` approach:** 1. Efficient use of resources: Only relevant nodes are notified when an event is published. 2. Easy to implement and maintain: Simple subscription and unsubscription mechanisms. **Cons of `pubSub` approach:** 1. Additional overhead due to DOM manipulation (event handling, element creation). 2. Potential performance issues if too many subscribers are registered for a single topic. **Custom Event Approach (`customEvent`)** The custom event approach uses the Web Events API to publish events. In this implementation: * A `PubSub` class is defined with a constructor that creates a custom event bus (a DOM element). * The `subscribe` method allows subscribers to register their callback functions for specific topics. * The `publish` method publishes an event on the topic, creating a custom event and dispatching it on the event bus. **Pros of custom event approach:** 1. Native Web API support, reducing additional overhead. 2. Built-in event handling mechanisms (e.g., event listeners). **Cons of custom event approach:** 1. Additional complexity due to the need to handle events programmatically. 2. Potential issues with event propagation and cancellation. **Comparison** The benchmark results show that: * `pubSub` outperforms `customEvent` by a significant margin (~120x), indicating that the additional overhead of the custom event approach is substantial. * The two `pubSub` implementations have similar performance characteristics, suggesting that the code is well-optimized and consistent. **Conclusion** The benchmark results suggest that for high-performance applications, the native Web Events API (used in the custom event approach) may be a better choice than a custom implementation of the Pub-Sub pattern. However, for ease of implementation and maintenance, a well-designed `pubSub` approach can still offer good performance characteristics.
Related benchmarks:
Date.now() vs new Date() vs performance.now()
Date.now() vs Moment()
MomentJS vs Native test
Date.now() vs new performance.now()
Date.parse vs new Date()
Comments
Confirm delete:
Do you really want to delete benchmark?