var adder = {
add: function(x, y) { return x + y; }
};
var a = (function() {
var outer = 1;
return {
add: function(x, y) { return adder.add(x, y); }
};
})();
for(var i = 0; i < 1000; ++i) {
console.log(a.add(5,6));
}
var b = (function(adder) {
var outer = 1;
return {
add: function(x, y) { return adder.add(x, y); }
};
})(adder);
for(var i = 0; i < 1000; ++i) {
console.log(b.add(5,6));
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Variant 1 | |
Variant 2 |
Test name | Executions per second |
---|---|
Variant 1 | 242.8 Ops/sec |
Variant 2 | 245.5 Ops/sec |
Let's dive into the details of this JavaScript microbenchmark, MeasureThat.net.
What is tested?
The benchmark tests two different variants of a module pattern implementation for a simple addition function, add
. The test case uses a self-invoking anonymous function (IIFE) to create an object with the add
method. The add
method takes two arguments and returns their sum using the provided adder.add(x, y)
syntax.
Options compared
The benchmark compares two variants:
outer
variable.adder
object as an argument and uses it to implement the add
method.Pros and Cons of each approach
Variant 1
Pros:
Cons:
outer
variable, which might lead to unexpected behavior in certain situations (e.g., closure-related issues)Variant 2
Pros:
adder
object, reducing memory allocation and garbage collection overheadCons:
adder
object as an argument, which might be less readable or intuitive for some developersOther considerations
The benchmark does not test other aspects of JavaScript implementation, such as:
Additionally, the benchmark only tests the add
method's performance, without evaluating its correctness or error handling.
Library usage
In this benchmark, the adder
object is used as a library. The adder.add(x, y)
syntax is an extension to the standard JavaScript +
operator for addition. This allows users to easily create and reuse modules with a simple addition function.
Special JS feature or syntax
The self-invoking anonymous function (IIFE) in both variants is a feature of modern JavaScript. It's used to create an immediately invoked function expression, which wraps the code inside itself and executes it immediately.
In summary, this benchmark tests two different module pattern implementations for a simple addition function, comparing their performance and memory usage. The results provide insights into the trade-offs between creating a new scope and reusing an existing object for better modularity and performance.