Skip to content

Instantly share code, notes, and snippets.

@jherr
Created December 22, 2020 01:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jherr/e4fbeaefb26cef81edc1fafee190dff8 to your computer and use it in GitHub Desktop.
Save jherr/e4fbeaefb26cef81edc1fafee190dff8 to your computer and use it in GitHub Desktop.
import * as NanoTimer from "nanotimer";
import { get } from "lodash";
const foo = {
bar: {
baz: 1,
},
};
const iterateWithOptionalChaining = () => {
let value = 0;
for (let i = 0; i < 1000000; i += 1) {
value += foo?.bar?.baz ?? 0;
}
return value;
};
const iterateWithGet = () => {
let value = 0;
for (let i = 0; i < 1000000; i += 1) {
value += get(foo, "bar.baz", 0);
}
return value;
};
const timerA = new NanoTimer();
const ocTime = timerA.time(iterateWithOptionalChaining, "", "u");
const getTime = timerA.time(iterateWithGet, "", "u");
console.log(ocTime); // 4097.653
console.log(getTime); // 125579.824
console.log(getTime / ocTime); // 30.646768772270367
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment