I have code that changes a bool only time in the setup(), and in my loop() I have
if (setupBool) {
// ...
} else {
// ...
}
Is checking the bool every loop slower than having a while(true) with the same code?
And what about checking it in every loop in a while(true)?
Is there any reason I shouldn't do those?
2 Answers 2
Of course an if statement cost time, although very little. However, it changes (although once), so if you need to vary depending on the value, you have to use the if statement.
A while(true) also cost a little time (a little bit less), but less than 1 us, same as the if statement. You can do perfectly do an if statement within the while(true), but remember, the loop itself is behaving like a while(true) already.
However, I wouldn't concern at all about optimizing performance, unless:
- You know beforehand you will need the fastest code possible
- You have already performance issues
Always prefer readability/maintainability about performance.
The actual full structure of the loop function is like this:
- while(true)
- Call loop()
- if (condition)
- Run your code
- else
- Run your other code
- if (condition)
- Check for serial data
- Call loop()
By putting a while(true)
inside your if
you:
- Remove the overhead of calling
loop()
every time - Remove the overhead of checking for serial data (that is what the
SerialEvent
system is all about) - Remove the overhead of checking the
if
every iteration.
So the executing part of your code now looks like:
- while(true)
- Run your code.
If your code needs to run in a tight loop it can provide some speed improvements, yes, but at the cost of:
- No SerialEvent processing (normal Serial works, but the SerialEvent system breaks)
- Harder to "get out" of the loop to do something else (although
break
can help with that). - On ESP8266 boards the watchdog will time out unless you manually
yield()
regularly.
Would I suggest doing it? Well, there are times when it can be beneficial, but those times are few and far between. If you don't need to do it then, in general, don't do it.
while(true)
can be an alternative toif()...else...