var event = { foo: 'foo', bar: 'bar'}
var result = null
function getName1(event) { return event.foo }
function getName2(event) { return event.foo + event.bar }
var flag1 = true
var flag2 = false
result = {name: getName1(event)}
result = {name: getName2(event)}
result = {name: flag1 ? event.foo : event.foo + event.bar }
result = {name: flag2 ? event.foo : event.foo + event.bar }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Function call 1 | |
Function call 2 | |
Conditional operator 1 | |
Conditional operator 2 |
Test name | Executions per second |
---|---|
Function call 1 | 222974800.0 Ops/sec |
Function call 2 | 121300424.0 Ops/sec |
Conditional operator 1 | 223257152.0 Ops/sec |
Conditional operator 2 | 120363984.0 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Purpose
The benchmark is designed to compare the performance of different approaches in JavaScript: function calls versus conditional operators (ternary operators). The goal is to determine which approach is faster.
Script Preparation Code
The script preparation code defines two functions, getName1
and getName2
, which take an object as input and return a string. These functions are used in the benchmark test cases. Additionally, two variables, flag1
and flag2
, are defined with values of true and false, respectively.
Html Preparation Code
The html preparation code is empty, indicating that no HTML content is required for this benchmark.
Test Cases
There are four test cases:
foo
property of the input object.bar
property instead of just foo
.foo
or evaluating the entire condition.flag2
is false.Library
The benchmark does not explicitly use any JavaScript libraries. However, it relies on the browser's built-in JavaScript engine and its implementation of the functions and operators being tested.
Special JS Features/Syntax
None of the test cases rely on special JavaScript features or syntax beyond basic arithmetic operations, function calls, and ternary operators.
Pros and Cons of Approaches
Benchmark Results
The benchmark results show that the order of execution matters: the conditional operator approach is generally faster than the function call approach, especially when evaluating simple expressions.
Other Alternatives
If you're interested in exploring alternative approaches to this benchmark, consider the following:
let
or const
instead of var
for variable declarationsKeep in mind that the performance differences between these approaches may be subtle and dependent on specific use cases.