typestar

local.tee in WebAssembly

Store a value and keep using it, in one instruction.

(module
  ;; local.tee stores like local.set but leaves the value on the
  ;; stack, so one computation can feed a local and the next step.
  (func (export "square_plus_orig") (param $n i32) (result i32)
    (local $doubled i32)
    (i32.add
      (local.tee $doubled (i32.mul (local.get $n) (i32.const 2)))
      (i32.mul (local.get $doubled) (local.get $doubled)))))

How it works

  1. local.tee $doubled (...) writes the local and leaves the value.
  2. The kept copy feeds i32.add while the local feeds the square.
  3. Without tee this takes a set and an extra get.

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
342
Tokens
57
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 53 seconds.

Type this snippet

Step 2 of 3 in Locals & the stack, step 8 of 28 in Language basics.

← Previous Next →