Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Which is more efficient? the formula or the function?

Ok, I am trying to make a math library for myself to experiment stuff so, I came up with a case where you want to find the distance btw 2 points. Now everyone normally uses this (p1 - p2).magnitude Well, I am not great at maths and stuff, so I refer my academic textbooks (ugh) and here's how I made a distance function

function module.Distance(p1, p2)
	return math.sqrt((p1.X - p2.X)^2 + (p1.Y - p2.Y)^2 + (p1.Z - p2.Z)^2)
end

I am wondering which is the best to use.....

=3

3 comments

0

I'm pretty sure magnitude is more efficient... You don't need to use so much math when you can simply say "magnitude" and it gives you the distance

0

xd, I am wondering that too xD, but the other is more close to maths so MATHS MATHS MATHS X-X

0

I would say the formula, not the function.

2 answers

✓ Accepted answer

I just tested it, magnitude is better. I tested it by measuring how long it took to do it multiple times using tick(). This is the code I used:

wait(2)
print("Starting")
p1 = Vector3.new(34,54,76)
p2 = Vector3.new(13,1,98)

times = 1000000

it = tick()

for i=1, times do
	this =  math.sqrt((p1.X - p2.X)^2 + (p1.Y - p2.Y)^2 + (p1.Z - p2.Z)^2)
end

result1 = tick() - it
it = tick()

for i=1, times do
	this = (p1-p2).magnitude
end

result2 = tick() - it
if result1 < result2 then -- Math time is less than magnitude time
	print("Math is better")
elseif result2 < result1 then -- Magnitude time is less than math time
	print("Magnitude is better")
else
	print("They are both the same")
end

print("Result 1 = " .. result1)
print("Result 2 = " .. result2)

Try it out if you want, it should say Magnitude is better for whatever you use for p1 and p2

1 comment

0

Cool.

I believe that the formula is more efficient because the less code you can use to get something done the better and also the easier it will be to review your code. So I believe that the magnitude formula would be best to use for what you are trying to achieve.

I hope I helped and thank you for reading this answer!

3 comments

0

I agree with your answer, but highly disagree with how you got to it. Just because something uses less code, does not mean it's more efficient.

0

=3

0

Wouldn't it be so that the less code a script executes the least amount of lag and it will go way smoother wouldn't that be what you mean by "efficient". Less lag and more smoothness = Efficiency.

This discussion is preserved as it was. New answers, comments, and votes are closed.