Let's say you have a lot of For/Next cycles going on and you desperately need to improve your computing speed. What would you do?
I came up with this idea, reducing all the cycles into a single one.
Would this be a good technique?
Before:
B4X:
Sub Whatever(Value as int)
...
'Do Stuff
...
End Sub
Sub Example
Dim array_x(512)
Dim array_y(1024)
Dim array_z(256)
Populate_Array(x)
Populate_Array(y)
Populate_Array(z)
For i = 0 to (array_x.Lenght - 1)
Whatever(array_x(i))
Next
For i = 0 to (array_y.Lenght - 1)
Whatever(array_y(i))
Next
For i = 0 to (array_z.Lenght - 1)
Whatever(array_z(i))
Next
End Sub
After:
B4X:
Sub Whatever(Value as int)
...
'Do Stuff
...
End Sub
Sub Example
Dim array_x(512)
Dim array_y(1024)
Dim array_z(256)
Populate_Array(x)
Populate_Array(y)
Populate_Array(z)
For i = 0 to (Max(array_x.Lenght, Max(array_y.Lenght, array_z.Lenght)) - 1)
Select True
Case i < array_x.Lenght
whatever(array_x(i))
Case i < array_y.Lenght
whatever(array_y(i))
Case i < array_z.Lenght
whatever(array_z(i))
End Select
Next
End Sub
I understand. So, it's better to optimize my condition checks, rather than the number of cycles, right?
By the way, what do you think it's faster? IF's or SELECT's?
Also, in a general IF-THEN-ELSE-...., I would choose the first condition as the more likely to be true (so the "else" condition will have to be evaluated less frequently)
Making a function call in an inner loop also has some overhead regardless of the method used. So, instead of
B4X:
For i = 0 to (array_x.Lenght - 1)
Whatever(array_x(i))
Next
I would try
B4X:
Sub WhateverToAllArrayElements(Values() as int)
for k=0 to Values.len-1
...'Do Stuff ...
next
End Sub
Sub Example
...
WhateverToAllArrayElements(array_x)
WhateverToAllArrayElements(array_y)
WhateverToAllArrayElements(array_z)
...
end sub
this seems to run at the same speed as the original tripple loop one and 17 times faster than the select/case.
B4X:
Sub Example3
Dim array_x(512) As Int
Dim array_y(1024) As Int
Dim array_z(256) As Int
For i = 0 To (array_y.Length - 1)
If i<511 Then
Whatever(array_x(i))
If i<255 Then Whatever(array_z(i))
End If
Whatever(array_y(i))
Next
End Sub