Identifying Octal Strings
JavaScript performance comparison
Info
Each test must return true for all numbers that would be interpreted by major web browsers as an octal number, but in the string type.
Remember that all acceptable octal numbers begin with any number of zeroes (i.e. "0..."). Furthermore, remember that a negative octal number would lead with a negative sign (i.e. "-0...").
Important note: There MUST be an assumption that the string does contain a number! This means that simply searching for the number "0" at the beginning of the string (allowing for a negative sign) is sufficient.
Second important note: Since the string is unlikely to be an octal string, I have tested for "false" a greater number of times than true.
Third important note: Treating numbers beginning with "0" as an octal number does not appear to be part of the official specification, despite the default behaviour of popular web browsers.
Preparation code
<script>
Benchmark.prototype.setup = function() {
var octalString = "012345";
var nonOctalString = "12345";
var longOctalString = "-00123456789123456789";
var longNonOctalString = "123456789123456789";
function charAt(str) {
if (str.charAt(0) === "0" || (str.charAt(1) === "0" && str.charAt(0) === "-")) {
return true;
};
};
function regExp(str) {
if (/^0/.test(str)) {
return true;
};
};
function indexOf(str) {
var num = str.indexOf("0");
if (num === 0 || (num === 1 && str.indexOf("-") === 0)) {
return true;
};
};
function indexOfTwo(str) {
var num = str.indexOf("0");
if (num === 0 || (num === 1 && str < 0)) {
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… |
regExp |
|
pending… |
indexOf |
|
pending… |
indexOfTwo |
|
pending… |
You can edit these tests or add even more tests to this page by appending /edit to the URL.
0 comments