I'm not sure if people ever noticed this with the 0.4 Squirrel releases, but vectors have some added functions for doing basic mathematical calculations on points/vectors, including:
- Vector.Distance(Vector other) - calculates the distance between two points, returns the distance as a float
- Vector.Length() - calculates and returns the magnitude of a point (from point 0, 0, 0) as a float
- Vector.Dot(Vector other) - calculates and returns the dot product between two points as a float
- Vector.Normalize() - alters the vector so that it is a unit vector such that Length() returns 1
I think prior to this, people mostly used the in-built sqrt() function in Squirrel to calculate the distances between points. I was curious to see if this would incur a performance penalty, since the vector functions exist in C++ in the Squirrel core, whereas sqrt() might be interpreted by Squirrel instead.
I did some basic benchmarking and as it turns out,
Vector.Distance is more efficient than using sqrt(x^2 + y^2 + z^2). More interestingly, it seems that Vector.Distance can be
as much as 10x faster.
Benchmark codelocal start = 0;
local elapsed = 0;
local i;
local distance;
local point1 = Vector(867.5309, 2.201, 3.44);
local point2 = Vector(-3.75, -3.691, 3.1415926);
print("Point1: " + point1);
print("Point2: " + point2);
//-------------------------------------------//
start = GetTickCount();
for (i = 0; i < 1000000; i++) {
local dx = point2.x - point1.x;
local dy = point2.y - point1.y;
local dz = point2.z - point1.z;
distance = sqrt(dx * dx + dy * dy + dz * dz);
}
print("Sqrt distance: " + distance);
elapsed = GetTickCount() - start;
print("Sqrt loop: " + elapsed + "ms");
//-------------------------------------------//
start = GetTickCount();
for (i = 0; i < 1000000; i++) {
distance = point1.Distance(point2);
}
print("Call distance: " + distance);
elapsed = GetTickCount() - start;
print("Call loop: " + elapsed + "ms");
//-------------------------------------------//
This isn't to say that slow code is because you're using sqrt, or that everyone should immediately get to work on converting their code to use Vector.Distance, because this is micro-optimizing. The benchmarks were done over
a million iterations (1,000,000) and so this would have no significant impact unless you were calculating vector distances very often. I just thought it was fun to note, since mathematical operations are typically pretty fast even in scripting languages.