var a = "Here's a string value";
var b = 5; // and a number
var c = false;
var object = {
a, b, c
}
var array = [
a, b, c
];
var passObject = (obj) => {
return obj.a.length + obj.b * obj.c ? 2 : 1;
}
var passRawValues = (val_a, val_b, val_c) => {
return val_a.length + val_b * val_c ? 2 : 1;
}
var passArray = (arr) => {
return arr[0].length + arr[1] * arr[2] ? 2 : 1;
}
var passNothingUseGlobalVars = () => {
return a + b * c ? 2 : 1;
}
var passNothingUseGlobalObject = () => {
return object.a.length + object.b * object.c ? 2 : 1;
}
var passNothingUseGlobalArray = () => {
return array[0].length + array[1] * array[2] ? 2 : 1;
}
var x = 0;
x << 1;
x ^= passRawValues(a, b, c);
x << 1;
x ^= passObject(object);
x << 1;
x ^= passArray(array);
x << 1;
x ^= passObject({a, b, c});
x << 1;
x ^= passArray([a,b,c]);
object.a = a;
object.b = b;
object.c = c;
x << 1;
x ^= passObject(object);
array.a=a;
array.b=b;
array.c=c;
x << 1;
x ^= passArray(array);
x << 1;
x ^= passNothingUseGlobalVars();
x << 1;
x ^= passNothingUseGlobalObject();
x << 1;
x ^= passNothingUseGlobalArray();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Pass raw values | |
Pass object | |
Pass array | |
Pass new object | |
Pass new array | |
Pass modified object | |
Pass modified array | |
Global vars | |
Global object | |
Global array |
Test name | Executions per second |
---|---|
Pass raw values | 2689004.5 Ops/sec |
Pass object | 3896395.8 Ops/sec |
Pass array | 3869444.2 Ops/sec |
Pass new object | 2684526.8 Ops/sec |
Pass new array | 2673640.5 Ops/sec |
Pass modified object | 1756238.2 Ops/sec |
Pass modified array | 1758767.8 Ops/sec |
Global vars | 2622284.2 Ops/sec |
Global object | 2706401.8 Ops/sec |
Global array | 2821887.8 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares the performance of different ways to pass data to a function in JavaScript. The functions are not explicitly defined, but we can infer their behavior based on the code. There are four main approaches:
Test Results
The benchmark results show the number of executions per second for each test case, which represents the performance of passing data to the functions. The top three performers are:
Key Takeaways
From the results, we can conclude that:
This benchmark highlights the importance of understanding how variables are passed to functions in JavaScript. In general, it's recommended to use arrays or objects for passing data to avoid potential issues with variable scope and modification.
The fact that global scope is not the fastest way to pass data may indicate that there are other factors at play, such as caching or optimization techniques used by the JavaScript engine.
Keep in mind that this benchmark is specific to the implementation of JavaScript and may vary depending on the browser, platform, or other factors.