Identifying Hexadecimal Strings
JavaScript performance comparison
Info
Each test must return true for all numbers that would be interpreted by major web browsers as a hexadecimal number, but in the string type.
Remember that all acceptable hexadecimal numbers begin with "0x...", where the "x" may be uppercase. Furthermore, remember that a negative hexadecimal number would lead with a negative sign (i.e. "-0x...").
Important note: There MUST be an assumption that the string does contain a number! This means that simply searching for the letter "x" (uppercase or lowercase) is sufficient.
Second important note: Since the string is unlikely to be a hexadecimal string, I have tested for "false" a greater number of times than true.
Preparation code
<script>
Benchmark.prototype.setup = function() {
var hexString = "0x12345";
var nonHexString = "12345";
var longHexString = "-0X123456789123456789";
var longNonHexString = "123456789123456789";
function charAt(str) {
if (str.charAt(1).toLowerCase() === "x" || str.charAt(2).toLowerCase() === "x") {
return true;
};
};
function charAtTwo(str) {
if (str.charAt(1) === "x" || str.charAt(2) === "x" || str.charAt(1) === "X" || str.charAt(2) === "X") {
return true;
};
};
function regExp(str) {
if (/x/i.test(str)) {
return true;
};
};
function indexOf(str) {
if (str.toLowerCase().indexOf("x") > -1) {
return true;
};
};
function indexOfTwo(str) {
if (str.indexOf("x") > -1 || str.indexOf("X") > -1) {
return true;
};
};
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
charAt |
|
pending… |
charAtTwo |
|
pending… |
indexOf |
|
pending… |
indexOfTwo |
|
pending… |
regExp |
|
pending… |
You can edit these tests or add even more tests to this page by appending /edit to the URL.
0 comments