For Statements and declaring counter in the For

When I first started learning XOJO over ten years ago there were many tricks for improving speed.
One of them is "Do Not define your counter in the For statement because it gets (constantly redefined or whatever).

Did this speed trick become useless

1 Like

AFAIK if you do your length calculation in the For line, it still recalculates on each iteration which has a penalty. You should also avoid declaring variables within your loop body or calling outside functions when you can.

3 Likes

In 99% of all my for loops I do the loop variable in the loop or the loop check in the loop declaration. Here is a random example:

for currentMenuItem as Integer = 0 to RecentItemsQueue.LastIndex
  RecentItemsQueue(currentMenuItem).isDisabled = False
next

The recent items are 10 folderitems. Does it matter if I call LastIndex for 10 folderitems? No, it does not matter.

for currentMenuItem as Integer = 0 to RecentItemsQueue.LastIndex

here i think “as integer” is only allocated once and LastIndex is in manual mentioned as method which should called each iteration and could be noticeable in slow down because the nature of methods (process flow).
as beatrix said, optimization is need if execution at all is very slow or noticeable by yourself or the user.
optimization can make source code unreadable and could have consequences or result in unwanted bugs.

1 Like

What @Anthony_G_Cyphers said. But for what is worth; this is not “trick”. It applies to any other language that allows such declarations within a loop. If the compiler cannot tell beforehand what that declaration will resolve to, it has no way of optimizing it out (even if the compiler is capable of that level of optimization). So as a general rule; it is better to declare as close to the usage point (in this case the loop), but outside the loop itself. That the language allows for these type of declaration is very nice because it allows for readability and more compact programming; but in the purest sense it is not good practice to do so.

for currentMenuItem as Integer = 0 to XXX

And that XXX may be evaluated on each loop. If that is a function doing work, it may cost performance.
So I usually put the loop bound in a local variable to only calculate it once.

I’ve tested this in the past and, in practice, the difference will amount to a few milliseconds over thousands of iterations. I’ve done it this way for speed-critical code like encryption or hashing, but in the overwhelming number of my cases, it’s not worth sacrificing readability and scope.

4 Likes

Well, the problem often is that if you call a property, you may expect it to be a variable, but some properties have a getter function, which takes considerable time to finish.

But of course until you see it being slow and you search for places where to cut off a few %, you may find that.

1 Like