Blog>
Snippets

Benchmarking Access Speed

Benchmark performance comparison between accessing properties in an object created with Object.create(null) and a regular object with prototype.
// Create a null object and a regular object
const nullObject = Object.create(null);
const regularObject = {};

// Assign a property to both objects
nullObject.prop = 'value';
regularObject.prop = 'value';

// Function to measure the access speed
function benchmarkAccess(object, iterations) {
  const startTime = performance.now();
  for (let i = 0; i < iterations; i++) {
    // Access the property
    const value = object.prop;
  }
  const endTime = performance.now();
  return endTime - startTime;
}

// Benchmark both objects
const iterations = 1000000;
const nullObjectDuration = benchmarkAccess(nullObject, iterations);
const regularObjectDuration = benchmarkAccess(regularObject, iterations);

console.log(`Null object access time: ${nullObjectDuration}ms`);
console.log(`Regular object access time: ${regularObjectDuration}ms`);
This code sets up a benchmark test to compare the property access speed between a null object (an object without a prototype) and a regular object (with a prototype). Each object has a property assigned to it, and the benchmarkAccess function measures the time taken to repeatedly access that property for a given number of iterations. The times for the null object and the regular object are then logged to the console.