Skip to content

Instantly share code, notes, and snippets.

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 stevendaniels/4576474 to your computer and use it in GitHub Desktop.
Save stevendaniels/4576474 to your computer and use it in GitHub Desktop.
Is it faster to use regex to detect a browser's os, or indexOf?
//methodology: ran the test 4 times and took the slowest time.
checkOSRegex = function(){
var os = navigator.platform;
return /[wl]in/i.test(os) ? /win/i.test(os) ? 'linux' : 'windows' : 'mac'; //slightly confusing, but 26% faster than
}
checkOSRegexStart = Date.now();
for(var i = 0; i < 1000000; i++){
checkOSRegex('MacIntel');
checkOSRegex('Linux i686');
checkOSRegex('Win32');
checkOSRegex('Commodore64');
}
chcekOSRegexTime = Date.now() - checkOSRegexStart; //7416 milliseconds
checkOSIndexOf = function(){
var platform = navigator.platform.toUpperCase();
if(platform.indexOf('MAC')!==-1)
return 'mac';
else if(platform.indexOf('WIN')!==-1)
return 'win';
return 'linux'
}
checkOSIndexOfStart = Date.now();
for(var i = 0; i < 1000000; i++){
checkOSIndexOf('MacIntel');
checkOSIndexOf('Linux i686');
checkOSIndexOf('Win32');
checkOSIndexOf('Commodore64');
}
chcekOSIndexOfTime = Date.now() - checkOSIndexOfStart; //9340 mi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment