I have a script in a game with a function that gets called every second. Distances between player objects and other game objects are calculated every second. The problem is that within 1 second there can be 800 function calls (maximum 40 players * 2 main objects (from 1 to 10 sub-objects)). I have to optimize this function for less processing. this is my current function:
local square = math.sqrt;
local getDistance = function(a, b)
local x, y, z = a.x-b.x, a.y-b.y, a.z-b.z;
return square(x*x+y*y+z*z);
end;
-- for example followed by: for i = 800, 1 do getDistance(posA, posB); end
I found out that the localization of the math.sqrt function through
local square = math.sqrt;
- great optimization regarding speed, and code
x*x+y*y+z*z
faster than this code:
x^2+y^2+z^2
I don't know if localizing x, y, and z is better than using the class method "." twice, so maybe square(a.x*b.x+a.y*b.y+a.z*b.z)better than codelocal x, y, z = a.x-b.x, a.y-b.y, a.z-b.z;
square(x*x+y*y+z*z);
Lua?