KScript docs
EN

The language

How scripts run

kscript compiles each block of statements the first time it runs, so a loop or a function called many times runs as .NET code rather than being read again on every pass. Inside a function body or a loop body, the variables the block declares are kept in numbered slots instead of a scope, which is what makes number-heavy code (a knapsack, a grid search, a simulation) several times faster. A body with a loop, or one that has run 64 times, is then compiled again into a single .NET method, so a tight loop over numbers runs about twice as fast again. A loop in that method whose work is numbers and lists (arithmetic, comparisons, reading and setting list items, if, while and for over a range) also gets a second copy that takes its variables to be exactly that, which is several times faster still; the moment a value turns out to be something else, the loop carries on in the general copy from the same statement. A function that passes fn(x) => ... to a method such as ->map() keeps its slots too, as long as each variable the callback reads is set once, before the callback is made. A loop over a range such as 0..1000000 counts through it without making the list. Nothing about a script changes: the same values, the same errors at the same line and column, and the debugger still steps through every statement, because a debugged script is always interpreted.

A few environment variables exist to compare them, for example when reporting a bug that only shows up in one of them: KSCRIPT_INTERPRET=1 turns compilation off, KSCRIPT_NO_REGIONS=1 compiles but keeps every variable in a scope, KSCRIPT_NO_TREES=1 keeps slots but never makes the single .NET method, and KSCRIPT_NO_LOOPS=1 makes the method without the second copy of its loops.