just built my first project with Arduino. Was hoping to optimize it in a few ways (reduce global variables, lesser string variables etc.) when i stumbled upon a few posts saying that delay() was for beginners and that millis() was more useful when multi-tasking... although using either is entirely dependent on the context of the application. I use delay() several times in my project, especially when I want text to be displayed for a minimum amount of time on an LCD screen.
However, I was wondering if delay() could always be replaced by millis() - would that be "optimizing" my code ? please let me know.
"millis()" is not a drop in replacement for "delay()".
See the "Blink Without Delay" Example in the IDE. It is a different approach to do time management.
The most obvious impact of delay() vs millis() timing is when you are needing something to perform an action 'now' - e.g. a button press or critical event / message incoming.
Using delay(5000) - e.g. wait for 5 seconds while something is happening... note that nothing - means NOTHING - including the button press or other time critical event - wil lbe handled until the delay period is complete.
With well structured program flow, millis() (or any other similar non-blocking method), can check your input triggers far more often - allowing the button or external event to happen 'immediately'. The delay()s become irrelevant, because your program is 'event' driven, not bound to 'waiting' for some fixed time period to be complete.
Note - you will also learn about 'debouncing' slow events, because the processor is much faster than the switch contacts...
Then you may look into 'state-machines' which allow a number of things to happen (apparently at the same time) in almost any order.
Optimize for what?
Your code probably not became faster or shorter with millis(). But if you need that your program be able to do something else while the waiting for delay() is finished - you probably need to replace delay() with millis.
But if you program shouldn't do anything during the delay() - you don't need to change the code.