Skip to content

Instantly share code, notes, and snippets.

@tachekent
Last active September 11, 2018 18:45
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 tachekent/708cd1ceec94aa9a53df2f2ee52cf3d8 to your computer and use it in GitHub Desktop.
Save tachekent/708cd1ceec94aa9a53df2f2ee52cf3d8 to your computer and use it in GitHub Desktop.
Test if a joined regexp is faster than a simple array lookup
// needs node >= 8.5
const { PerformanceObserver, performance } = require('perf_hooks');
const URL = '/api/v1/admin/dashboard';
const ROUTES_ARRAY = [
'/api/v1/admin/dashboard',
'/api/v1/user/private',
'/api/v1/user/public',
'/api/v1/webhook'
];
const ROUTE_EXEMPTIONS = new RegExp('^(' + ROUTES_ARRAY.join('|') + ')', 'i');
const obs = new PerformanceObserver((items) => {
console.log(items.getEntries()[0].duration);
console.log(items.getEntries());
performance.clearMarks();
});
obs.observe({ entryTypes: ['measure'] });
performance.mark('A');
regexplookup(() => {
performance.mark('B');
performance.measure('A to B', 'A', 'B');
});
performance.mark('C');
arraylookup(() => {
performance.mark('D');
performance.measure('C to D', 'C', 'D');
});
function regexplookup(callback) {
for (i=0;i<1000000;i++) {
ROUTE_EXEMPTIONS.test(URL);
}
callback();
}
function arraylookup(callback) {
for (i=0;i<1000000;i++) {
ROUTES_ARRAY.forEach((route) => {
URL.indexOf(route);
});
}
callback();
}
@tachekent
Copy link
Author

Regexp Lookup:

53.835653
[ PerformanceEntry {
    duration: 53.835653,
    startTime: 439669652.471017,
    entryType: 'measure',
    name: 'A to B' } ]

Array Lookup:

284.145556
[ PerformanceEntry {
    duration: 284.145556,
    startTime: 439669711.964357,
    entryType: 'measure',
    name: 'C to D' } ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment