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

Why are some calculations faster than others?

So I wanted to test some calculations and how fast they run and I found some interesting stuff that I hope someone can explain for me. For example, I have these 2 functions:

local a = {
	function( a, b )
		return a * a * a * a + ( b * a * a * a ) + ( b * b * b * a ) + ( b * b * a * a );
	end;
	
	function( a, b )
		return a ^ 4 + ( b * a ^ 3 ) + ( b ^ 3 * a ) + ( b ^ 2 * a ^ 2 );
	end;
}

I ran multiple iterations of each function and found that the first one takes almost half as much time as the second one, why is this? I thought the first one would take longer because it's more complex so it takes more memory so I guess not.

Also another example would be these 4 functions, which I found even more strange:

local c = {
	function( a, b )
		return ( a * a * a ) ^ 0.5 + ( b * b * b ) ^ 0.5 - ( a * a * a * a * a ) ^ 0.5 - ( b * b * b * b * b ) ^ 0.5;
	end;
	
	function( a, b )
		return math.sqrt( a * a * a ) + math.sqrt( b * b * b ) - math.sqrt( a * a * a * a * a ) - math.sqrt( b * b * b * b * b );
	end;
	
	function( a, b )
		return a ^ 1.5 + b ^ 1.5 - a ^ 2.5 - b ^ 2.5;
	end;
	
	function( a, b )
		return a ^ ( 3 / 2 ) + b ^ ( 3 / 2 ) - a ^ ( 5 / 2 ) - b ^ ( 5 / 2 );
	end;
};

The 2nd function always took the longest, almost twice as long as the other three, but the other three functions were never consistent with their performance. Sometimes the first function would run faster than the other 2, sometimes the 3rd or sometimes the 4th. Can someone explain to me why this is so?

Thanks

1 answer

Disclaimer: I am not a replacement for your computer science teacher, and it's definitely a good idea to ask them about what goes on behind the instructions. Alternatively, ask somebody who actually took and completed computer science.


Put simply, some instructions are just a lot more explicit and simple than others. Multiplying something multiple times instead of using the power operator skips the part where it decides exactly how to treat that power (Fractional powers and negative powers are of course different to just multiplying something multiple times), and multiplying is almost always faster than dividing (Where folding is not in place)

With your sqrt vs ^ implementation, there's the additional overhead of actually sorting out the fact that it's being put into a function, but also the slight difference in the implementation - Whereas the math.sqrt function uses the C sqrt function, the ^ uses the C pow (And metamethod invocation) function. Probably. I actually didn't look for the source for the ^ operator. If you're interested, there's a comparison of pow vs sqrt performance, however different tests from different sources appear to yield varying results.

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