Skip to content

Instantly share code, notes, and snippets.

@aquapi
Last active September 27, 2024 11:56
Show Gist options
  • Save aquapi/c509497ea9a849f2f18b923b94d566a2 to your computer and use it in GitHub Desktop.
Save aquapi/c509497ea9a849f2f18b923b94d566a2 to your computer and use it in GitHub Desktop.
import { group, run, bench } from 'mitata';
// Do warmup
for (let i = 0; i < 10; i++) bench('noop', () => { });
group('Set vs array vs literal', () => {
// Do checks with arrays
const arr = ['hi', 'there', 'nagna', 'randomlongstring', 'small'];
const arrInclude = (item) => arr.includes(item);
// Do checks with set
const set = new Set(arr);
const setHas = (item) => set.has(item);
// Do checks with objects
const obj = {};
for (let i = 0, l = arr.length; i < l; ++i) obj[arr[i]] = null;
const objHas = (item) => obj[item] === null;
const objHas2 = (item) => item in obj;
// Generate a function which compares the input string to all strings in the list
const rawHas = Function(`return (i)=>${arr.map((str) => 'i===' + JSON.stringify(str)).join('||')};`)();
// Generate strings
const newArr = [];
for (let i = 0; i < 100000; i++)
newArr.push(Math.random() < 0.5 ? `${Math.random()}` : arr[Math.round(Math.random() * 4)]);
bench('Array', () => newArr.map(arrInclude));
bench('Set', () => newArr.map(setHas));
bench('Object', () => newArr.map(objHas));
bench('Object 2', () => newArr.map(objHas2));
bench('Raw', () => newArr.map(rawHas));
});
run();
// The raw method is faster because static string comparisons can be
// optimized to ptr-to-ptr comparison
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment