I’ve always felt that software is often a superiorly legible form of math, and math is a more verbose/inferiorly-complicated form of psudo-code/software, but taking Calculus has opened my eyes to some things (namely taking the derivative / limit as a number approaches infinity, which would be impossible to do accurately using a naive for loop.)
This has me wondering (TLDR:)
If Lua were a low level language like C++, would this:
local sum = 0
for i=1,4 do
sum = sum + 5
end
print(sum)
be as efficient as this?
print(5*4)
Similarly, would this:
local total = 1
for i=1,4 do
total = total*5
end
be as efficient as this?
print(5^4)
Is it basically doing this behind the scenes anyway?
I know Lua is interpreted, so it’s slower, but would these two pieces of code be equal in efficiency if Lua was a compiled language?
Not at all as efficient, for many different reasons. But this really comes down to what the CPU has to actually do in order to run the code you wrote. In C++, most modern compilers are probably smart enough to do loop unrolling to get that code to run faster.
AFAIK, all modern CPUs have instructions to multiply numbers, which means it will always be faster than making the CPU add them over and over.
Generally speaking (really generally), algorithms (e.g. your for loop) are going to perform slower than a pure mathematical solution to the same problem.
I know Lua is interpreted, so it’s slower, but would these two pieces of code be equal in efficiency if Lua was a compiled language ?
No, Lua is compiled into bytecode instructions and those instructions are executed by the VM or a program depending on where you use Lua. Lua is compiled.
No, because it is not possible to do so without getting unexpected behavior. However, Lua does use constant folding. So a expression like 5/6 * 10 / 16 is already solved before code execution. That expression is folded to 0.52083333333333333333333333333333.
The more widely used compilers like Clang or GCC even detect patterns that replicate the behavior of built in instructions. Often times code like that would be emitted as a single multiplication instruction too.
Multiplication has one assembly instruction whereas with a loop you have a lot of jumps and jumps are relatively expensive so a multiplication is definitely faster (and more readable)