Private Fields vs Public Properties

Benchmark created on


Test runner

Ready to run.

Testing in
TestOps/sec
Private Fields
// Test for private fields
class WithPrivate {
  #field = 0;
  increment() { this.#field++; }
  get() { return this.#field; }
}

const privateTest = () => {
  const obj = new WithPrivate();
  const iterations = 10000000; // 10 million iterations
  
  console.time('PrivateFieldTest');
  for (let i = 0; i < iterations; i++) {
    obj.increment();
  }
  console.log(obj.get()); // Ensure the value is used
  console.timeEnd('PrivateFieldTest');
};

privateTest();
ready
Public properties
// Test for public properties
class WithPublic {
  field = 0;
  increment() { this.field++; }
  get() { return this.field; }
}

const publicTest = () => {
  const obj = new WithPublic();
  const iterations = 10000000; // 10 million iterations
  
  console.time('PublicPropertyTest');
  for (let i = 0; i < iterations; i++) {
    obj.increment();
  }
  console.log(obj.get()); // Ensure the value is used
  console.timeEnd('PublicPropertyTest');
};

publicTest();
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.