Object property lookup fastest implementation (v3)

Revision 3 of this benchmark created on


Preparation HTML

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

Setup

const objectsToLookupPropertyIn = new Array(10_000).fill(0).map((_, index) => ({
  coreData: {
    status: `hooray-${index}`,
    subStatus: {
      mode: `mode-${index}`,
      user: `user-${index}`,
      moreThings: `moreThings-${index}`,
    },
  }
}));

const lookupLocations = [
  'status',
  'subStatus.mode',
  'subStatus.user',
  'subStatus.moreThings'
];

const maxRandomNumber = (lookupLocations.length - 1);

const allLookups = new Array(10).fill(0).map((_, index) => {
  const indexOfLookup = Math.floor(Math.random() * (lookupLocations.length - 1));
  return lookupLocations[indexOfLookup];
});

Test runner

Ready to run.

Testing in
TestOps/sec
Use a map!
const getItMap = (data) => (propertyPath) => {
  const map = new Map([
    ["status", data.coreData.status],
    ["subStatus.mode", data.coreData.subStatus.mode],
    ["subStatus.user", data.coreData.subStatus.user],
    ["subStatus.moreThings", data.coreData.subStatus.moreThings],
  ])

  return map.get(propertyPath);
};

objectsToLookupPropertyIn.forEach(data => {
	allLookups.forEach(propertyPath => {
		getItMap(data)(propertyPath);
	});
});
ready
lodash get
// Requires: <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
const getItLodash = (data) => (propertyPath) => {
  return _.get(data.coreData, propertyPath);
};

objectsToLookupPropertyIn.forEach(data => {
	allLookups.forEach(propertyPath => {
		getItLodash(data)(propertyPath);
	});
});
ready
Manually look it up
const getItManually = (data) => (propertyPath) => {
  const parts = propertyPath.split('.');
  let currentValue = data.coreData;
    
  while(parts.length) {
  	if (!currentValue[parts[0]]) {
  		throw new Error(`Could not find ${parts[0]} ${JSON.stringify(currentValue)}`);
  	}
  	currentValue= currentValue[parts[0]];
  	parts.shift();
  }

  return currentValue;
};

objectsToLookupPropertyIn.forEach(data => {
	allLookups.forEach(propertyPath => {
		getItManually(data)(propertyPath);
	});
});
ready

Revisions

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