I'm trying to check whether the input string contains all digits or not. I achieved this using 2 different algos. One is to convert the string to integer using String.toInt() and then checking if its value lies between the integer of length of the input string.
e.g. If input string is "123". The corresponding integer must lie between 100-999.
Second, I wrote a function that iterates over each character of the string and checks if its ASCII values lies between 48-57. If not, it returns false.
When I bench marked these two algos, I found that when the string contains only digits, the 2nd algo is about 9 times faster than the 1st one. But when the string contains even a single non-digit character, the 1st algo takes ~1ms, but the 2nd algo always takes ~5ms. Why is this? I've not been able to figure this out.
The code:
unsigned long start;
unsigned long middle;
unsigned long end;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// send an intro:
Serial.println("String toInt():");
Serial.println();
}
void loop() {
// Read serial input:
if (Serial.available()) {
String r = Serial.readString();
start = micros();
unsigned long rInt = r.toInt();
int rLen = r.length();
if ((rInt >= floor(pow(10, rLen))) || (rInt < floor(pow(10, rLen-1)))) {
Serial.println("Please enter valid integer value!");
} else {
Serial.println(rInt+1);
}
middle = micros();
bool isInt = doesContainInteger(r);
if (isInt) {
Serial.println(r);
} else {
Serial.println("Please enter valid integer value!");
}
end = micros();
Serial.println(middle-start);
Serial.println(end-middle);
}
}
bool doesContainInteger(String s)
{
int sLen = s.length();
for (int i=0; i<sLen; i++) {
char sChar = s.charAt(i);
if (sChar<48 || sChar>57) {
return false;
}
}
return true;
}
"Please enter valid integer value!"
, just print"Invalid int"
. You will get somewhat less unrealistic timings."Please enter valid integer value!"
with"!"
, and it took just 80us to print.pow()
is a horrendously slow routine. Avoid it at all costs.