Honestly I haven’t liked using DistToSqr when doing distance checks because the numbers I have to work with are somewhat annoying,
not a very good reason to not use it especially in a piece of code that was for example, used for rendering or in a loop that is called often.
I did some testing and found that DistToSqr is only very slightly faster. Using the following code:
local function profileAverage(taskItr, task, averageItr)
local mean = 0;
for j = 1, averageItr do local start = SysTime(); for i = 1, taskItr do task(i); end mean = mean + (SysTime() - start); end return mean / averageItr;
concommand.Add(“profile”, function(ply, cmd, args)
local itr = 1000 * 100;
local avg = 10;
print("disttosqr: " .. profileAverage(itr, function(i) -- assign global so that this can't be ignored as a useless operation to perform -- maybe jit does this i'm not sure dist = Vector(i, i, i):Distance(Vector(-i, -i, -i)) end, avg)); print("distance: " .. profileAverage(itr, function(i) dist = Vector(i, i, i):DistToSqr(Vector(-i, -i, -i)) end, avg)); print("sqrdist custom: " .. profileAverage(itr, function(i) local a = Vector(i, i, i); local b = Vector(-i, -i, -i); dist = (a.x - b.x) + (a.y - b.y) + (a.z - b.z); end, avg));
I got these results:
disttosqr: 0.11867651725609 distance: 0.11770560799648 sqrdist custom: 0.23249257654688
Which means a single call to DistToSqr over a call to Distance is (on average) 100ns (0.0001milliseconds) faster. Is this a relevant number anywhere?
To put the negligibility of this number into perspective, I wanted to use a function like this to simplify my life:
local meta = FindMetaTable(“Vector”);
function meta:DistLessThan(b, dist)
return self:DistToSqr(b) < (dist ^ 2);
But the difference between using this and not using a function (as a calling a function will obviously impact things slightly) is 11 times worse than
calling Distance over DistToSqr.