More Optimizations¶
Besides numbers, calls and tables, there are a few more places where compiled code saves work. This page goes over them.
Conditions¶
A comparison in an if, while or repeat, or combined with and, or and not, jumps on the
result directly. No true or false value is made just to be tested right after.
A condition that's always true, such as while true do, costs nothing at all. Testing a local
(if name then) reads it where it is, and a value whose type is already known, such as a field
just read, is true without asking the host unless it's a boolean.
Local Variables¶
A new local lives where its value was computed, just as in the interpreter. In
local item = list[i] the value is read and that's all: it isn't copied anywhere else. The
variables of a for ... in loop likewise stay where each round puts them.
for i = 1, #rows do
local row = rows[i]; -- one read
local name, size = row.name, row.size;
ListBox.AddItem("Files", name .. " (" .. size .. ")", i);
end
Concatenation¶
a .. b .. c .. d joins all four in one go, just like the interpreter does, instead of three times
two. Long string building such as this is one operation:
Library Functions¶
A few library functions are computed natively when your code calls the host's own version:
| Function | Native when |
|---|---|
math.sqrt(x) |
x is a number |
math.floor(x) |
x is a number |
math.ceil(x) |
x is a number |
math.abs(x) |
x is a number |
math.min(a, b, ...) |
Every argument is a number, and the last one isn't a call or ... |
math.max(a, b, ...) |
Every argument is a number, and the last one isn't a call or ... |
type(x) |
Always; compared with a name, type(x) == "table", no string is made at all |
select("#", ...) |
In a function with ... |
select(i, ...) |
In a function with ..., i a number |
string.byte(s, i), s:byte(i) |
s is a string in a local, i from 1 to its length |
string.sub(s, i, j), s:sub(i, j) |
s is a string in a local |
string.len(s), s:len() |
s is a string in a local |
tonumber(x) |
Always, without a base: a number stays, a string converts as the host converts it |
string.unpack(fmt, s, pos) |
Lua 5.3: fmt is a constant of one integer of up to 8 bytes, such as ">I4", and the bytes are in s |
In Lua 5.3 the positions must be integers, and in Lua 5.1 whole numbers, for the native version. Anything else makes the real call, so the host decides, errors included.
tonumber(x) converts a string with the host's own conversion, so "0x10", " 5 " and "1e3"
give what they give in the interpreter, and in Lua 5.3 "10" stays an integer and "10.0" a
float. string.unpack reads its first value from the string's bytes; with a format of more than
one value, alignment (!) or anything but an integer, the host does it.
local unpack = string.unpack;
for i = 1, 16 do
w[i] = unpack(">I4", block, (i - 1) * 4 + 1); -- four bytes, no call
end
local checksum = 0;
for i = 1, #text do
checksum = (checksum + text:byte(i)) % 65521; -- no call per character
end
local function length(x, y)
return math.sqrt(x * x + y * y); -- a single machine instruction for the root
end
Each call still looks up the function first. If it isn't the host's own function, because a script
replaced math.sqrt with something else, the call is made as usual. Arguments that aren't simple
numbers also make the real call, so the host raises its own error for them.
Library functions called through their table, such as string.format(...) or table.insert(...)
as a statement, read the table and the function once, without moving them around.
Storing the function in a local works just as well, and saves the lookup:
local min, max = math.min, math.max;
local function clamp(value, low, high)
return max(low, min(high, value)); -- two comparisons, no calls
end
Lua 5.3 Integers¶
Bitwise operators (&, |, ~, <<, >>) and integer division and remainder (//, %) on
integers are computed natively, with exactly Lua 5.3's rules. Shifts of 64 bits or more give 0,
negative shifts shift the other way, and // and % round toward minus infinity. Division by zero
raises the interpreter's error, with its line.
The same goes for values read at run time, such as table elements, fields, bytes of a string and the results of calls: an expression over them checks once that they're all integers, and then computes natively. A float, a string or a table with metamethods takes the ordinary code, which converts, raises or runs the metamethod exactly as the interpreter does. Locals given such values inside a loop keep them natively.
local function hash(s)
local h = 5381;
for i = 1, #s do
h = ((h << 5) + h + s:byte(i)) & 0xFFFFFFFF;
end
return h;
end
Machine Code¶
The native backend turns all of this into machine code for x86 or x64:
- Variables that are used often inside a loop live in processor registers for the whole loop, those of inner loops first. On x86, numbers that no call in between could disturb live in registers too.
- Arithmetic works on those registers directly, with the other operand from a register, memory or a constant.
- Comparisons jump on the processor's flags directly.
- Jumps to jumps are shortened, and code is laid out so the common path runs straight through.
- Loops are tested at the bottom, so each round ends with a single jump back.
- Values that were just computed stay in their register for the next instruction.
- On x86, numbers are passed to functions in one 8-byte store, which the processor can read back right away.
Technical details
- Library functions are recognised by comparing the called value with the host's function, recorded when the module is loaded. This assumes the libraries are the host's own when the module is loaded, which is always the case for the standard libraries.
- Lua 5.3
math.floorandmath.ceilgive an integer when the result fits, and a float otherwise, natively too. math.minandmath.maxkeep the first of equal values, and never pick a NaN after the first argument, as the host's loop does. In Lua 5.3 the result is one of the arguments, somath.max(1, 1.0)is the integer1.math.absofmath.minintegerismath.mininteger, as in the host.type(x)asks the host for the value's type (lua_type), which is whattypedoes itself. Compared with a nametypenever gives, such as"Table", the condition is false.- On x86, a Lua 5.3 integer is 64 bits wide, so it takes two 32-bit registers, or two halves in memory. Adding a constant to a counter changes it in memory, and comparisons read the other operand from memory. Division goes through a helper.
- On x64, registers used in loops are the processor's non-volatile ones, saved when the
function starts and described in the DLL's unwind information, so errors unwind cleanly
through compiled code. On x86, numbers live in
xmm2toxmm7only when they are never live across a call, since no call keeps those registers. string.subpositions count from the end when negative and are clamped to the string, as the host does; a subject that's a number makes the real call, which converts it.- For Setup Factory 9.7 x64, a field with a fixed name (
t.name,t["name"], a global, a method) is read and written by pushing the name with its length (lua_pushlstring, thenlua_gettableorlua_settable). That host'slua_getfieldandlua_setfieldmeasure the name with a slow processor instruction on every call; the other hosts don't, and use them.