Skip to content

Instantly share code, notes, and snippets.

@jridgewell
Created August 11, 2022 23:40
Show Gist options
  • Save jridgewell/659bbd90bd6534565ecd10a4721d1565 to your computer and use it in GitHub Desktop.
Save jridgewell/659bbd90bd6534565ecd10a4721d1565 to your computer and use it in GitHub Desktop.
Class Fields vs This Assignment vs Object.defineProperty(this) (https://jsbench.github.io/#659bbd90bd6534565ecd10a4721d1565) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Class Fields vs This Assignment vs Object.defineProperty(this)</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/1.0.0/benchmark.min.js"></script>
<script src="./suite.js"></script>
</head>
<body>
<h1>Open the console to view the results</h1>
<h2><code>cmd + alt + j</code> or <code>ctrl + alt + j</code></h2>
</body>
</html>
"use strict";
(function (factory) {
if (typeof Benchmark !== "undefined") {
factory(Benchmark);
} else {
factory(require("benchmark"));
}
})(function (Benchmark) {
var suite = new Benchmark.Suite;
Benchmark.prototype.setup = function () {
class ClassFields {
a = Math.random();
b = Math.random();
}
function Assignment() {
this.a = Math.random();
this.b = Math.random();
}
function DefinePropertyNonEnumerable() {
this.a = Math.random();
this.b = Math.random();
}
function DefinePropertyNonEnumerableShorthand() {
this.a = Math.random();
this.b = Math.random();
}
function nonEnumerable(obj, prop, value) {
Object.defineProperty(obj, prop, { value, writable: true, enumerable: false });
}
function nonEnumerableShorthand(obj, prop, value) {
Object.defineProperty(obj, prop, { value, writable: true });
}
};
suite.add("const obj = new ClassFields();", function () {
const obj = new ClassFields();
const c = obj.a < 0.5 ? 'a' : obj.b < 0.5 ? 'b' : 'c';
});
suite.add("const obj = new Assignment();", function () {
const obj = new Assignment();
const c = obj.a < 0.5 ? 'a' : obj.b < 0.5 ? 'b' : 'c';
});
suite.add("const obj = new DefinePropertyNonEnumerable();", function () {
const obj = new DefinePropertyNonEnumerable();
const c = obj.a < 0.5 ? 'a' : obj.b < 0.5 ? 'b' : 'c';
});
suite.add("const obj = new DefinePropertyNonEnumerableShorthand();", function () {
const obj = new DefinePropertyNonEnumerableShorthand();
const c = obj.a < 0.5 ? 'a' : obj.b < 0.5 ? 'b' : 'c';
});
suite.on("cycle", function (evt) {
console.log(" - " + evt.target);
});
suite.on("complete", function (evt) {
console.log(new Array(30).join("-"));
var results = evt.currentTarget.sort(function (a, b) {
return b.hz - a.hz;
});
results.forEach(function (item) {
console.log((idx + 1) + ". " + item);
});
});
console.log("Class Fields vs This Assignment vs Object.defineProperty(this)");
console.log(new Array(30).join("-"));
suite.run();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment