I'm finishing up on a project and now I'm looking for ways to optimize my code. I'm using local variables whenever possible, calling print(F()) instead of print(), and in general trying to use smaller variable types and eliminate redundancies.
The one thing I haven't optimized yet is the big block of code (around 150 lines) that runs inside my loop() function. This block could be transferred to it's own function, which I would then call from loop(), but are there any performance/memory usage improvements to be gained calling a function from loop() instead of just running it there? Every part of the block that runs repetitive behavior is already calling other functions to do so, so there pretty much isn't any repeated code within it.
What feature are you trying to optimize? Smaller source code size? Smaller object code size? Faster running program? Each one will have an affect on other optimization desires. Using local variables makes for smaller program size on the Arduino, but make the program run slower. Using print(F()) also makes the program smaller, but run slower.
Anything using a loop of any kind makes a smaller source code, but runs slower than long stringy code.
Making more functions makes for smaller source code, but, in turn, makes more instructions to be executed.
You need to decide what you are optimizing for.
Paul
I'm trying to achieve a balance between speed and memory usage, although speed is preferred. I actually didn't know that using print(F( and local variables slowed down my code, and I might reconsider its uses (naturally, once the project is done, all Serial.print commands will be commented, since I won't be monitoring the Serial port). Right now I was planning on using even more conditional loops to make for a more readable code, but am also reconsidering. Guess I'll try to make it faster then.
My coding philosophy is to make the code as clear as possible and optimize when I must.
So yes, I'd move those 150 lines out of loop. The cost is likely to be minimal compared to how long those lines execute and you may find that the compiler inlines it for you anyway.
Even so, 150 sounds like too many for a single function - I like to be able to see the whole thing on one page and see at a glance what it does. My monitor can't manage the first and my brain can't do the second
Honestly same, that's why this doubt arrived when the IDE said I was running low on memory. I've always tried to slightly optimize my code, but this was the first time I had to get a grip and really optimize it.
It's mostly nested conditional expressions. I've been trying to simplify the contents of each one and it's already gone down quite significantly. Haven't tested it though, fingers crossed it works and doesn't impact performance too much.