Object property lookup fastest implementation

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(1000).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(100_000).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) => {
  _.get(data.coreData, propertyPath);

  return map.get(propertyPath);
};

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

  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.