I have recently taken a whole different approach in my coding style, I used to do stupid things like this...
Old approach (stupid):
New approach:
Even better:
I won't deny that both the second and third approaches looks uglier, but this kind of approach (caching!) does perform a lot faster, especially when scaled by orders of magnitude. In my current project, this kind of clean-up lowered my cycle time from ~0.32ms to ~0.27ms.
For want of a nail the shoe was lost.
For want of a shoe the horse was lost.
For want of a horse the rider was lost.
For want of a rider the message was lost.
For want of a message the battle was lost.
For want of a battle the kingdom was lost.
And all for the want of a horseshoe nail.
Old approach (stupid):
B4X:
'This is not real code, just the quickest example I could come-up with in Notepad++
Dim sizeX = 280 As Int
Dim sizeY = 480 As Int
Dim gridSize = 10 As Int
For x = 0 To (sizeX - 1)
For y = 0 To (sizeY - 1)
Dim pX = (x * gridSize) + (gridSize / 2) As Float 'Why, why, why??? LoL!!!
Dim pY = (y * gridSize) + (gridSize / 2) As Float
DrawCircle(pX, pY, gridSize / 2)
Next
Next
New approach:
B4X:
'Initialization
Dim sizeX = 280 As Int
Dim sizeY = 480 As Int
Dim gridSize = 10 As Int
'Cache
Dim lastX = sizeX - 1 As Int
Dim lastY = sizeY - 1 As Int
Dim halfGridSize = gridSize / 2 As Float
Dim pX, pY As Float
'Main Cycle
For x = 0 To lastX
pX = (x * gridSize) + halfGridSize 'There's no need to repeat this calculation 480 times in the Y cycle! Duh!
For y = 0 To lastY
pY = (y * gridSize) + halfGridSize
DrawCircle(pX, pY, halfGridSize)
Next
Next
Even better:
B4X:
'Initialization
Dim gridSize = 10 As Int
Dim sizeX = 280 / gridSize As Int
Dim sizeY = 480 / gridSize As Int
'Cache
Dim halfGridSize = gridSize / 2 As Float
'There's no need to cache lastX and lastY for the For cycle.
'If you're using a Do While Loop Until cycle however, it's a different story.
'Main Cycle
For x = halfGridSize To (sizeX * gridSize) Step gridSize
For y = halfGridSize To (sizeY * gridSize) Step gridSize
DrawCircle(x, y, halfGridSize) 'Only one instruction, whoohooo!!!
Next
Next
I won't deny that both the second and third approaches looks uglier, but this kind of approach (caching!) does perform a lot faster, especially when scaled by orders of magnitude. In my current project, this kind of clean-up lowered my cycle time from ~0.32ms to ~0.27ms.
For want of a nail the shoe was lost.
For want of a shoe the horse was lost.
For want of a horse the rider was lost.
For want of a rider the message was lost.
For want of a message the battle was lost.
For want of a battle the kingdom was lost.
And all for the want of a horseshoe nail.
Last edited: