Variables:
Bad:
Good:
Now, let's have a look at the junk we just got rid of:
Power() function algorithm in Java:
Sqrt() function algorithm in Java:
Happy coding!
B4X:
'pX: Point X-coordinate
'pY: Point Y-coordinate
'cX: Circle center X-coordinate
'cY: Circle center Y-coordinate
'cR: Circle Radius
Bad:
B4X:
'- Function calls are expensive. We have 2: Power() and Sqrt()
'- The Power() function itself is more expensive than simple multiplication (see why below)
'- The Sqrt() function itself is an iterative function that should always be avoided.
Sub isPointInCircle(pX As Double, pY As Double, cX As Double, cY As Double, cR As Double) As Boolean
Return Sqrt(Power(cX - pX, 2) + Power(cY - pY, 2)) <= cR
End
Good:
B4X:
'- No function calls
'- No Sqrt()
'- No Power()
Sub isPointInCircle(pX As Double, pY As Double, cX As Double, cY As Double, cR As Double) As Boolean
'----------------------------------------
'DistanceSquared = (dX * dX) + (dY * dY)
'RadiusSquared = (cR * cR)
'Return DistanceSquared < RadiusSquared
'----------------------------------------
Dim dX = cX - pX As Double
Dim dY = cY - pY As Double
Return (dX * dX) + (dY * dY) <= (cR * cR)
End
'Note that I commented DistanceSquare and RadiusSquared,
'instead of declaring them as variables or function calls.
Now, let's have a look at the junk we just got rid of:
Power() function algorithm in Java:
Sqrt() function algorithm in Java:
Happy coding!
Last edited: