Last active
September 11, 2018 18:45
-
-
Save tachekent/708cd1ceec94aa9a53df2f2ee52cf3d8 to your computer and use it in GitHub Desktop.
Test if a joined regexp is faster than a simple array lookup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Regexp Lookup:
Array Lookup: