Loop Optimization

Kria's compiler and VM include specialized paths for some recognized counter-loop patterns, global arithmetic, array iteration, and string appends. These optimizations are pattern-dependent; do not assume every loop is lowered to a single instruction.

Counted Loop Pattern

The fastest loops follow this pattern:

set i = 0
while (i < 1000000) {
    set i = i + 1
}

The compiler may recognize this counter-loop pattern and emit specialized bytecode. Verify performance with a benchmark rather than assuming the optimization is applied to every variation.

Loop Structure Tips

  • Use while for condition-based loops
  • Use for-in to iterate arrays and objects
  • Avoid function calls in hot loops when possible
  • Minimize operations in loop bodies

Algorithm Patterns

Kria supports powerful algorithms. Here are some common patterns:

Prime Number Check

fn is_prime(n) {
    if (n < 2) {
        return false
    }
    if (n == 2) {
        return true
    }
    
    set divisor = 2
    while (divisor * divisor <= n) {
        set remainder = n - (divisor * (n / divisor))
        if (remainder == 0) {
            return false
        }
        set divisor = divisor + 1
    }
    return true
}

GCD (Greatest Common Divisor)

fn gcd(a, b) {
    while (b != 0) {
        set temp = b
        set remainder = a - (b * (a / b))
        set a = temp
        set b = remainder
    }
    return a
}

Fibonacci (Recursive)

fn fibonacci(n) {
    if (n <= 1) {
        return n
    } else {
        set n1 = n - 1
        set n2 = n - 2
        return fibonacci(n1) + fibonacci(n2)
    }
}

Recursive algorithms are powerful but can be slow for large inputs due to repeated calls. Consider memoization or iterative approaches for better performance.

Best Practices

  • Use appropriate data structures — Arrays for sequences, objects for key-value data
  • Minimize scope — Define variables only where needed
  • Avoid deep nesting — Refactor complex logic into functions
  • Cache computed values — Store results you'll use multiple times
  • Profile before optimizing — Measure to find actual bottlenecks
  • Use built-in functions — They are optimized in the VM

Benchmarking

wait() pauses execution; it does not measure elapsed time. For reproducible measurements, use the benchmark suite in the Kria language repository. It compares equivalent workloads and reports VM execution separately from compilation, process time, and startup overhead.

Kria workload templates are in benchmarks/kria/. They use the .krx.in suffix because the runner replaces {{N}} with the selected workload size before executing them as Kria source files. Run node benchmarks/run.mjs from the language repository root; the default run uses both small and large sizes, with two warmups and seven measured runs.

WorkloadWhat the Kria template doesSmall / large size
arithmeticInteger arithmetic in a counted loop2,000,000 / 8,000,000
branchingCounted loop with a conditional branch2,000,000 / 8,000,000
nested-loopsNested loops accumulating both indexes1,500 / 3,500
function-callsRepeated calls to a two-argument function750,000 / 3,000,000
recursionSum of Fibonacci values using naive recursion20 / 25
closuresRepeated calls to a function using a multiplier750,000 / 3,000,000
arraysAppend integers, traverse the array, and sum it150,000 / 600,000
objectsRepeated property reads/writes with a checksum150,000 / 600,000
stringsRepeated single-character concatenation8,000 / 20,000

Note: despite its workload name and suite description, the current closures.krx.in template assigns factor at the top level. Under Kria's current name-resolution rules that is a global lookup, not a captured function-local upvalue, so this case should not be treated as a benchmark of lexical closure capture.

fn timed_operation() {
    set i = 0
    while (i < 1000000) {
        set i = i + 1
    }
}

print("Starting workload...")
timed_operation()
print("Completed workload")

The example above runs a workload but does not time it. For the repository suite, Node.js 16.6 or newer is required; Python is optional.

When optimizing:

  • Test with realistic data sizes
  • Consider both time and readability
  • Measure equivalent workloads and report the workload size and run settings
  • Separate VM execution time from compilation and process startup time