// *class* defined in terms of OLOO
var class1 = {
set_property: function(name, value) {
this.properties[name] = value;
},
get_property: function(name) {
return this.properties[name];
},
get_p: function() {
return this.p;
},
set_p: function(val) {
this.p = val;
}
}
function inst_class1() {
var obj = Object.create(class1)
obj.properties = {}
obj.p = 0;
return obj;
}
// just an object with it's own methods
function inst_class2() {
return {
properties: {},
p: 0,
set_property: function(name, value) {
this.properties[name] = value;
},
get_property: function(name) {
return this.properties[name];
},
get_p: function() {
return this.p;
},
set_p: function(val) {
this.p = val;
}
}
}
// es6 class
class class3 {
set_property(name, value) {
this.properties[name] = value;
}
get_property(name) {
return this.properties[name];
}
get_p() {
return this.p;
}
set_p(val) {
this.p = val;
}
}
function inst_class3() {
var obj3 = new class3();
obj3.properties = {};
obj3.p = 0;
return obj3
}
// the test
function test(obj) {
var result = 0;
for (var i = 0; i < N; i++) {
obj.set_property(i, i*0.33);
result += obj.get_property(i);
obj.set_p(result);
result += obj.get_p();
}
return result;
}
var N = 1000000;
var result = test(inst_class1());
var result = test(inst_class2());
var result = test(inst_class3());
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
oloo | |
direct properties | |
classes |
Test name | Executions per second |
---|---|
oloo | 5.9 Ops/sec |
direct properties | 4.7 Ops/sec |
classes | 4.7 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Definition
The provided JSON represents a benchmark that tests the performance of three different approaches to create objects with methods:
var class1 = { ... }
.var obj = { properties: {}, p: 0 }
.class class3 { set_property(name, value) { ... } }
.The benchmark consists of a test function test(obj)
that:
N
times)Options Compared
The three approaches are compared in terms of performance. The options being tested are:
obj.set_property(i, i * 0.33)
).new
.Pros and Cons of Each Approach
Here's a brief summary:
var obj = { ... }
).Library Used
There is no explicit library mentioned in the benchmark definition. However, the Object.create()
method is used to create instances of the class1
object, which is a built-in JavaScript method.
Special JS Features or Syntax
The ES6 class syntax is used here, but it's not explicitly tested for performance. The other approaches are more traditional and don't rely on specific features or syntax.
Other Alternatives
If you want to test alternative approaches, you might consider:
Object.assign()
or Array.prototype.concat()
.