Loops II - Safety and Efficiency

Erel

B4X founder
Staff member
Licensed User
Longtime User
Please let me quote Donald Knuth:

Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.

This is especially true for beginners. You should choose the block construct that best match the problem you are trying to solve. Only if you actually see any performance issues with this specific code then you need to start optimizing it.
 

Informatix

Expert
Licensed User
Longtime User
You should choose the block construct that best match the problem you are trying to solve.

That's what optimization is all about. Choosing the appropriate data structure, algorithm, library, code organization, etc. All experienced developers do that along the way. They already know what's suited or not, what's fast or not, and they check the efficiency of their choices in case of doubt. Trying to optimize at the end is usually a very optimistic point of view because you may be stuck by all the bad choices that you made and your only solution will be to rewrite big chunks of code. What a time loss! We all knew this frustrating experience at least once. I cannot recommend doing the same.
Optimizing to gain a few milliseconds when this difference is absolutely imperceptible for the end user or doing complex things, hard to maintain, while performance is not expected is stupid, we all agree on that point. It's a caricature of what optimizing really means. But thinking that you can fix all your performance issues at the end is maybe not very clever too.
EDIT: the difference of speed between the loop structures above is about 30% between the fastest and the slowest on the devices that I used. Not neglectable depending on the case.
 
Last edited:

wonder

Expert
Licensed User
Longtime User

Replaced some of my "For i = 0" with "For Each".
43% speed boost confirmed!!
THANK YOU FRED!
 

Peter Simpson

Expert
Licensed User
Longtime User
Well this post makes for interesting reading, very interesting indeed @wonder.

Especially knowing that
B4X:
For Each Item As String In MyList
    ...
Next
 
Last edited:
Cookies are required to use this site. You must accept them to continue using the site. Learn more…