function Monster()
{
this.x = 100;
this.y = 100;
console.log("Monster created at " + this.x + " / " + this.y + "!");
}
function Monster2()
{
var that = this;
that.x = 100;
that.y = 100;
console.log("Monster created at " + that.x + " / " + that.y + "!");
}
new Monster();
new Monster2();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
this | |
that |
Test name | Executions per second |
---|---|
this | 41151.7 Ops/sec |
that | 43686.3 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Definition
The benchmark is defined as two test cases:
new Monster();
new Monster2();
These test cases create instances of the Monster
function and measure their performance.
Script Preparation Code
The script preparation code for both test cases is identical:
function Monster() {
this.x = 100;
this.y = 100;
console.log("Monster created at " + this.x + " / " + this.y + "!");
}
function Monster2() {
var that = this;
that.x = 100;
that.y = 100;
console.log("Monster created at " + that.x + " / " + that.y + "!");
}
Both test cases create an object with x
and y
properties, log a message to the console, and set this
(or that
) to point to the newly created object.
Options Compared
The benchmark compares two options:
this
: In the first test case (new Monster();
), the code uses this
to access the object's properties.new Monster2();
), the code uses a variable named that
(instead of this
) to access the object's properties.Pros and Cons
Here are some pros and cons for each approach:
Using this
:
Pros:
Cons:
this
(depending on the browser)Using a variable named "that":
Pros:
this
being overridden by other variables or functionsthat
Cons:
that
) that may consume more memoryLibrary Used
The benchmark uses a library called Lighthouse, which is a set of tools developed by Google to test website performance. Specifically, it's using the Chrome DevTools Protocol (CDP) to collect execution time data.
Special JS Feature/Syntax
There are no special JavaScript features or syntax used in this benchmark. It's purely a comparison of two simple assignment statements.
Other Alternatives
Some alternative approaches could be:
let
or const
instead of var
for the variable name() => { ... }
) instead of a traditional function declarationHowever, these alternatives would likely not change the fundamental comparison between using this
and a variable named "that".