"use strict";
class Foo {
constructor() {
this._bar = 1;
}
get bar() {
return this._bar;
}
getBar() {
return this._bar;
}
setBar(val) { this._bar = val; }
}
window.instance = new Foo();
var result = instance.bar;
instance.setBar(result + 1);
var result = instance.getBar();
instance.setBar(result + 1);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Getter | |
Method |
Test name | Executions per second |
---|---|
Getter | 3611506.8 Ops/sec |
Method | 3572795.0 Ops/sec |
I'd be happy to help explain the benchmark and its various components.
Benchmark Definition
The provided JSON defines a JavaScript microbenchmark, which measures the performance of two different approaches: accessing the bar
property using getter methods (getter
) versus method calls (method
). Here's a breakdown of the options being compared:
bar
property. This means that instead of writing instance.bar
, you would write instance.get bar()
. The getter returns the value of this._bar
.setBar
) to access and modify the bar
property.Pros and Cons
Here are some pros and cons of each approach:
In terms of performance, both approaches are generally similar. However, some studies suggest that getter methods might incur a small overhead due to the indirection.
Library Usage
The benchmark uses no external libraries beyond the standard JavaScript library.
Special JS Features or Syntax
There are no special JavaScript features or syntax being used in this benchmark.
Other Alternatives
In addition to getters and methods, there are other ways to access and modify properties:
instance.bar
(not tested in this benchmark).instance['bar']
(not tested in this benchmark).Additional Considerations
The performance difference between getters and methods might be negligible for simple cases. However, as the complexity of your code increases, the differences may become more pronounced. Additionally, some modern browsers have optimized getter methods, which can further reduce the overhead.
For a wider range of benchmarks, consider exploring other approaches to measuring performance, such as: