What makes a SCUA program fast or slow, and what you can change about it. The advice comes from profiling real programs: an image codec, simulation-heavy game use cases, HTTP handlers and the benchmark suite.
The short version:
- Measure the real workload before changing anything, and look at what
--jit-statsrefused. - Work out whether your time goes on your code (loops and arithmetic, which the JIT compiles) or on the runtime (lookups, allocation, string work and type checks, which it doesn't). The fixes are different.
- Most of the large wins come from the shape of your data: records for
fixed fields, arrays built with
[], one kind of number per array, enums instead of string tags. - A hot loop is fastest when it's small, in its own function, and not nested inside another loop.
#Measure first
#Time the thing you care about
- Time a run that's long enough to matter (a second or more) and representative of real use. A loop of ten iterations tells you about startup, not about your code.
- Use CPU time (
userintime's output) rather than wall time when you compare two versions, and run each version several times, alternating between them. On a laptop doing other things, differences under about 5% are usually noise. - Compare on the same machine. ARM (Apple silicon, ARM Linux) and x86-64 have different strengths, and a change can help one and not the other (see ARM and x86 differ).
- Check the output is identical before and after. A speed-up that changes an answer isn't one.
#Ask the JIT what it did
$ scua --jit-stats app.scua
[jit] mode=on compiled=12 native-entries=48210 deopts=31 ...
[jit] refused loop in update at line 40: a while loop nested inside this one (line 44) (x1)
compiled=above zero, with native entries to match, means hot code is running natively.- A
refusedline names a loop that stays at interpreter speed and says why. These are the cheapest wins on this page: fixing one often speeds that loop up several times. Make scripts run faster with the JIT lists what compiles and what to do about each refusal. - Many
deoptsrelative tonative-entriesmeans compiled code keeps falling back, usually because a value's kind changes from one call to the next.
#Compare against the interpreter
scua --jit=off app.scua runs the same program without
the JIT. If it is only slightly slower, your time is probably not in
code the JIT can help with, which is the next section's subject.
#Your code or the runtime?
The JIT turns your loops and functions into native code. It doesn't change the cost of the built-in work they ask for: looking a key up in a table, comparing two strings, allocating a record, checking an argument against its declared type, collecting garbage. That work happens in the runtime, at the same speed whether the code that asked for it was compiled or not.
The two kinds of program behave very differently:
- Arithmetic-heavy code, such as decoders, physics, numeric loops and bit manipulation, spends most of its time in your own instructions. Getting its hot loops compiled is what counts. In the image codec, compiling the bit reader and the decode loops took a progressive decode from 5.1 s to about 3 s.
- Data-structure-heavy code, such as simulations that walk game state, rule engines and business logic, spends most of its time in the runtime: table and array reads, allocation, garbage collection and type checks. In the game use cases we profiled, doubling the number of compiled functions moved their totals by only a few per cent.
For the second kind, the wins come from fewer lookups and
allocations, not from the JIT. A rough rule of thumb: if
--jit=off is less than about 1.5× slower than the default,
start with the next section.
#Shape your data for speed
#Use records for things with fixed fields
A record has a fixed layout, so p.hp is a
read at a known position, and the JIT can keep it in a register. A
record's declared field types are also what lets a typed parameter be
checked cheaply: after the first call, checking a record argument is a
quick test of its layout, not a field-by-field walk.
record Unit {
id: number,
hp: number,
speed: number,
}
A plain table with the same fields works too, and reading a field by
its written name (t.hp) is fast for both.
#Reading a table by a key computed at run time
-- price is a table of about a dozen entries, read with a key chosen at run time
let cost = price[item.kind]
A read like price.sword, with the name written in the
code, is the fastest kind: the position is looked up once and remembered
at that line. A read by a key that is only known at run time
(price[k]) can't be remembered that way. Each one is a call
into the runtime, which finds the key by comparing strings. That costs a
few tens of nanoseconds, against a nanosecond or so for a named read. It
rarely matters, but in a loop that does little else it can be most of
the loop's time.
When it does matter:
- Read by name where you can. If the key is one of a
few known names, a
matchorifthat readsprice.swordis faster. - Key by an enum or a number. If the key comes from a fixed set, make it an enum and index an array with it. An enum indexes an array by its position in the declaration, and indexing an array by a number is cheaper than any string lookup:
enum Kind { Sword, Shield, Bow }
const COST = [30, 20, 25] -- in the order Kind lists them
let k = Kind.Bow
print(COST[k])
$ scua costs.scua
25
- Look it up once. Hoist a lookup out of a loop into a local when the key doesn't change inside it.
#Build arrays with [], not
{}
let xs = [] -- an array
xs.push(1)
let ys = {} -- a table
ys[1] = 1 -- a table keyed by numbers, not an array
{} filled with t[i] = … gives you a hash
table keyed by numbers. It works, but every read is a hash lookup and
none of the array fast paths apply. Use [] and
push, or an array literal.
#Keep each array to one kind of value
An array whose elements are all integers, or all floats, is stored
packed: plain machine numbers with no per-element tag, which halves its
memory and lets compiled loops read it directly. SCUA does this
automatically. Store a value of a different kind (a string,
nil, or a float into an integer array) and the array falls
back to the general layout, permanently, for its whole life.
So keep "no value" out of numeric arrays (use a sentinel such as
-1, or a separate array of flags), and don't mix integers
and floats in one array.
Element-typed
buffers ({ f32 }, { u8 },
{ u16 } and so on) are for handing data to a host and for
saving memory with narrow number types. They are not faster than a plain
array of numbers, which is already packed.
#Use enums instead of string tags
Comparing two enum values is a single comparison. Comparing two
strings compares their length and hash, then their bytes. In a hot path,
state == State.Running is cheaper than
state == "running", and match on an enum is
cheaper than a chain of string comparisons.
#Build strings with a builder
s = s .. piece in a loop copies the whole string every
time round, so the loop gets slower as the string grows. Use
builder() and b.add(...), or collect the
pieces in an array and str.join them (see Strings). For
binary data, use bytes.join, not bytes.concat
in a loop.
#Put shared constant data at the top level
A top-level const, and a module's own constant tables
and functions, live in one read-only area that every partition reads in
place. Compiled code reads their fields once, when it compiles, and can
treat them as constants. That holds for large tables and modules
too.
Two things defeat this:
- Calling a module through a local alias.
mod.f(x)compiles;let m = modfollowed bym.f(x)currently keeps that function out of the JIT. Call the module by its own name in hot code. - Rebuilding constant data at run time. A lookup
table built in a function on every call has to be allocated and filled
each time. Make it a top-level
constinstead.
#Allocate less in hot loops
Every new record, table, array or string is an allocation, and allocations are what the garbage collector later has to scan. In the profiles, building a small record per result and pushing it onto an array was a visible share of the time.
- Return two numbers instead of a two-field record from a function that's called millions of times, when the record doesn't outlive the caller.
- Reuse a scratch array (clear it and refill it) rather than making a new one per iteration.
- Don't build strings for keys (
x .. ":" .. y) in a hot path. Use a number (y * width + x) instead.
#Help the JIT compile your hot code
The JIT compiles loops that run many times and functions that are
called many times, including small helpers called from a hot loop, which
it can copy into the loop. Most everyday code compiles: arithmetic
including % and //, bitwise operations,
comparisons, x == nil tests, field reads and writes on
records, array reads and writes, calls to methods on records, and reads
of top-level constants and module fields.
The things that most often keep a hot loop at interpreter speed are a loop nested inside it, a variable that holds different kinds of value on different paths, a very long function, and many calls in one loop. Make scripts run faster with the JIT gives the full list and what to do about each. Two habits avoid most of them:
- Keep a variable to one kind. Compiled code is
specialised for the kind of value it saw. Start a float total at
0.0, not0, and don't let a variable befalseon one path and a number on another. - Write small, single-purpose functions. A function that does one job with a short body is easy for the JIT to compile and to copy into its caller, and moving an inner loop into its own function lets both loops compile. A helper called millions of times costs almost nothing once compiled, but a lot if it isn't.
#ARM and x86 differ
- Registers. ARM has more registers to hold values, so a busy loop with several calls in it can compile on ARM and be refused on x86, or compile on both and run with more values in memory on x86. If a loop is refused only on x86, call fewer functions in its body or move it into a smaller function.
- Division. On x86, division by a constant is turned
into a multiply, which is very cheap. On ARM the hardware divide is
already fast. On both,
%by a power of two is a mask, soi % 8is cheaper thani % 7. - Measure on the machine you'll deploy on. A change that helps one architecture by 10% can be flat on the other.
#Concurrency
- Partitions are cheap: an idle one costs a few kilobytes and starting one takes about a microsecond. Use as many as your design wants.
- A message to another partition is copied. Sending a large table on every message costs a copy each time. Send an id or a small record, and keep the large data with the partition that uses it. Send large data once shows the pattern for a fan-out to several workers, with what it saves.
- Top-level constants aren't copied: every partition reads the same one in place. Shared reference data belongs there.
- Data made at run time can be shared the same way:
freezeit and send it. A frozen array, table, record or string of 64 KiB or more (1 MiB on Windows) is read in place by every partition it is sent to, so a fan-out that gives four workers the same data holds it once, and the sends cost nothing however large it is. Below that size a frozen value is copied, which takes microseconds.--mem-statsshows what is shared (shared=). In 0.42 and earlier, a message copies a frozen value like any other. freezecosts nothing for a value nothing else holds. Build the data in the function that freezes it, freeze it at its last use there, and it is frozen where it is, or moved into the shared area without copying a large array's storage. A value that is a parameter, is stored somewhere else, or is used after thefreezeis copied.--mem-statscounts both kinds (freezes-moved=andfreezes-copied=), so you can check that afreezeyou expect to cost nothing doesn't copy. See freeze.--workersspreads partitions across cores. Tasks inside one partition take turns, so CPU-bound work that should run in parallel needs separate partitions (see Partitions and actors).- When you measure,
--workers=0runs the partitions one at a time on one thread. That makes the timing of single-partition work steadier and the output order repeatable.
#A checklist for a slow program
- Time a representative run, and keep its output to compare against.
- Run with
--jit-stats. Fix anyrefusedline in a loop you know is hot. - Run with
--jit=off. If it's not much slower, your time is in the runtime: work through Shape your data for speed. - Look for strings used as tags,
{}used as an array, arrays that mix kinds, and tables read in a tight loop by a key computed at run time. - Look for allocation in the innermost loop: new records, tables, string keys.
- Re-measure after each change, and keep only the ones that moved the number.