B4J Question Compiler question

Ray Y

Member
Given:
For I = 0 To somelist.Size - 1

Is the expression "somelist.Size - 1" recomputed every loop iteration?
 

Ed Brown

Active Member
Licensed User
Longtime User
It should be - yes. This is because the list 'somelist' can change in size while inside the loop.

If the list does not change size then it is more efficient (with large lists) to set the another variable to the size of the list before the loop.
 
Upvote 0

Ed Brown

Active Member
Licensed User
Longtime User
Hmm, you're right. But this is also not the way it's meant to be. Why is B4J optimising the for/loop by assigning a variable (as my original suggestion)? There are times where this is not the desired behaviour and for B4J to simply just do this is WRONG and not the normal behaviour.
 
Upvote 0

KMatle

Expert
Licensed User
Longtime User
B4J to simply just do this is WRONG and not the normal behaviour

In VB.net it's the same. The FOR statement is initialized ONCE with the given values. Changing it later will not cause the FOR loop to finish (e.g. if it was 10 at start and now it's 5 it will not change the terminator of the FOR statement).
 
Upvote 0

Ray Y

Member
Programming 101: Don't use a FOR loop unless you know the number of times you want the loop executed. And certainly don't change the loop variables inside the loop. I scream every time I see:

B4X:
x = 10
For i = 1 to x
   do something
   if WeAreDone then x = 1
next i

Lazy lazy lazy. This is stuff C programmers do all the time. Drives me crazy. Plus, it makes debugging big loops a nightmare. This is what WHILE is for.

Anyway, I was just asking to know if I had to use a temp variable to store the computed result, or if it works the way _I_ think it should and optimizes it.

And I was too lazy to write my own test.

Thanks all.
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…