Lua: calculating code optimization vector length

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?

+3
5

Roberto Ierusalimschy Lua ( - Lua). , (, ). , : . 30 , .

, , , , , 't (, , , ).

: , . , , - , / UX , , - , .

, :

Lua, , :

№1: .

№ 2: . ( )

+8

, - .

, , , (tip: if a^2 < b^2 a > 0 b > 0, a < b) .. ..

+3

" " .

, /, , :

 +---------+--------------+
 | objects | calculations |
 +---------+--------------+ 
 |      40 |        1600  |
 |      45 |        2025  |
 |      50 |        2500  |
 |      55 |        3025  |
 |      60 |        3600  |
...       ...            ...
 |     100 |       10000  |
 +---------+--------------+

" ", .

, , " " , .

, , .

Player1 Player2, Player2 Player1. .

"". , . , . ; , , ).

, ; . :

http://en.wikipedia.org/wiki/Space_partitioning

+2

?

800 0,001 - Lua .

- , , ? "return (0)", , (, ).

, , ?

800 1 , 1987 .

+1

sqrt a,

x_0 = a
x_n+1 = 1/2 * (x_n + a / x_n)

x_n sqrt(a) n -> infinity. .

! , .

local getDistance = function(a, b)
    local x, y, z = a.x-b.x, a.y-b.y, a.z-b.z;
    return x+y+z;
end;

It is much easier to calculate in some cases (for example, if the distance is necessary to find out if two objects are close), it can act adequately.

0
source

All Articles