<!--your preparation HTML code goes here-->
const o = { f1(){}, f2: () => {}, f3: undefined}
o.f1()
o.f2()
o.f3?.()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
f1 | |
f2 | |
f3 |
Test name | Executions per second |
---|---|
f1 | 221880528.0 Ops/sec |
f2 | 221078864.0 Ops/sec |
f3 | 225731184.0 Ops/sec |
The provided benchmark evaluates the performance of three different JavaScript function invocation styles using an object o
that contains three methods: a standard function (f1
), an arrow function (f2
), and an undefined function (f3
). Here’s a detailed explanation of what is being tested, the options compared, their pros and cons, and some related considerations.
Standard Function (f1
):
f1
is defined as a standard function notation within the object o
(i.e., f1() {}
).o.f1()
Arrow Function (f2
):
f2
is defined as an arrow function (i.e., f2: () => {}
).o.f2()
Optional Chaining with Undefined (f3
):
f3
is defined as undefined
, but the invocation uses optional chaining (i.e., o.f3?.()
).o.f3?.()
The benchmark results show how many times each function can be executed per second in the environment tested, which was Chrome 133 on a Windows Desktop. Here are the raw execution rates:
f3
: 225,731,184 executions per secondf1
: 221,880,528 executions per secondf2
: 221,078,864 executions per secondf1
)Pros:
this
context.Cons:
f2
)Pros:
this
, making it easier to manage the context, particularly in functions within classes or objects.Cons:
new
).this
, which may lead to unexpected results in some situations.f3
)Pros:
Cons:
The benchmark provides clear insights into the execution performance of various JavaScript function styles. Each approach has its benefits and drawbacks, and it’s crucial for software engineers to choose based on the specific needs of their codebase, considering factors such as execution speed, context management, and readability.