Of course I can do it via comparing it to 10 digits or even using regular expressions, but I'm looking for the fastest way possible.
Here is what I currently came up with, does it look reasonable?
int _zero = "0".codeUnits[0];
int _nine = "9".codeUnits[0];
bool isDigit(String s, int idx) =>
s.codeUnits[idx] >= _zero && s.codeUnits[idx] <= _nine;
I'm a bit surprised that I haven't found this method in a standard library, hopefully I just missed it.
Try:
bool isDigit(String s, int idx) => (s.codeUnitAt(idx) ^ 0x30) <= 9;
for speed.
I ran a quick micro-benchmark for the various alternatives and it seems it is pretty much a tie between Günter's method and brute force checking. I prefer Günter's method for the elegance but if performance is absolutely critical, it seems brute force may win by a tiny margin. The benchmark runs each method once for an index that will return true and once for an index that will return false.
bool isDigit(String s, int idx) {
return s[idx] == "0"
|| s[idx] == "1"
|| s[idx] == "2"
|| s[idx] == "3"
|| s[idx] == "4"
|| s[idx] == "5"
|| s[idx] == "6"
|| s[idx] == "7"
|| s[idx] == "8"
|| s[idx] == "9";
}
0.045421617878512024 us.
bool isDigit(String s, int idx) =>
"0".compareTo(s[idx]) <= 0 && "9".compareTo(s[idx]) >= 0;
0.054188391470161947 us
int _zero = "0".codeUnits[0];
int _nine = "9".codeUnits[0];
bool isDigit(String s, int idx) =>
s.codeUnits[idx] >= _zero && s.codeUnits[idx] <= _nine;
0.6344102870896872 us
This can be improved by 2x by storing the results of s.codeUnits[idx] (for some reason the VM cannot manage to optimize this away, unlike the other methods where repetitive s[idx] calls are optimized and not slower than storing an intermediate result):
bool isDigit(String s, int idx) {
int cuIdx = s.codeUnits[idx];
cuIdx >= _zero && cuIdx <= _nine;
}
0.29245961607948817 us
RegExp digitRegExp = new RegExp(r'\d');
bool isDigit(String s, int idx) => s[idx].contains(digitRegExp);
4.812064808888846 us
bool isDigit(String s, int idx) {
bool isDigit = true;
try {
int.parse(s[2]);
} catch (e) {
isDigit = false;
}
return isDigit;
}
102.48526774276198 us
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With