Loop Optimization

Kria's VM includes combined loop instructions that optimize counting loops. The compiler recognizes patterns like i = i + 1 and generates specialized bytecode.

Counted Loop Pattern

The fastest loops follow this pattern:

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

This pattern compiles to a single specialized opcode, reducing dispatch overhead on each iteration.

Loop Structure Tips

  • Use while for counted loops
  • Use for-in for iterating collections
  • 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

Use wait() to measure execution time of code sections:

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

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

For more detailed benchmarking, wrap code sections and use system timing. The Kria repository includes performance test examples.

When optimizing:

  • Test with realistic data sizes
  • Consider both time and readability
  • Profile different approaches
  • Share benchmarks in pull requests for optimization PRs