1

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?

  • I don't understand how a while(true) can be an alternative to if()...else... – Dmitry Grigoryev Mar 6 '18 at 10:08
  • I couldn't understand why you are checking setupBool in the loop if it can change only in the setup... Moreover you usually don't need a while(true) in the loop since it automatically gets executed forever – frarugi87 Mar 6 '18 at 10:16
3

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.

2

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
    • Check for serial data

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.