---
title: "Sharing byte buffers and reusing coroutine frames"
description: "A byte-buffer snapshot and a child coroutine both reuse storage. We measured the cost of keeping track of that storage, then built the same Hew workloads for Arm and Intel."
source: "https://hew.sh/blog/2026/11/making-proven-lifetimes-cheaper"
---

One of our benchmarks gave a Hew actor four bytes, `b"abcd"`, and a 64-byte heap limit. The actor took 200,000 snapshots of the buffer. It read a byte from each snapshot, discarded the snapshot and returned the sum. We ran this handler on one worker.

```hew
#[max_heap(64)]
actor Reader {
    var data: bytes;

    receive fn sum(n: i64) -> i64 {
        var sum = 0;
        for i in 0..n {
            let view = clone data;
            sum += view[i % 4] as i64;
        }
        sum
    }
}
```

The four bytes stayed in place throughout the loop. Each snapshot shared the original backing allocation. The CPU still executed about 1,291 user-mode cycles per iteration on an Intel C4, measured across the process. Two parts of that cost showed up on opposite sides of the read.

## Creating the snapshot

Hew's original release build sent each clone through the runtime's general procedure for constructing an owned value. The compiler emitted a description of the input on the stack and called `hew_budget_materialize_begin` to obtain permission to construct the result. On success it retained the byte buffer, filled in the result and committed the reservation.

For a shallow copy of `bytes`, the compiler knew that the result would refer to the allocation held by the source. The [new lowering](https://github.com/hew-lang/hew/pull/4020) gave that source directly to the actor's budget check. This excerpt from the optimized LLVM IR shows how the runtime can refuse a copy before it becomes visible to the actor.

```llvm
%budget.alias = call i32 @hew_budget_acquire_alias(ptr null, ptr nonnull @__hew_budget_value_7, ptr nonnull %s0)
%budget.ok = icmp eq i32 %budget.alias, 0
br i1 %budget.ok, label %budget.accepted, label %bb7
```

The accepted branch increments the buffer's reference count. An actor receiving a handle to an allocation for the first time may have to charge it against its heap. One runtime test gave an owner a six-byte limit and acquired two handles to the string `"shared"`. The account held six bytes after both acquisitions. A request for a handle to a separate one-byte string failed with `HEAP_EXCEEDED`. Releasing the first handle left six bytes charged. Releasing the second brought the charge to zero.

## Dropping the snapshot

The general release procedure accepts a batch. Several entries can point to the same backing allocation, so the runtime groups the entries by identity and checks how many references it can release. For the snapshot in our loop, the whole batch contained one backing. The runtime was allocating a hash map with one entry on every pass.

The [single-backing release](https://github.com/hew-lang/hew/pull/4022) passes that identity and a reference count of one directly to the existing refund procedure. Batches with repeated identities still use the grouping step. Both paths validate the charges before changing the account.

<figure class="benchmark-figure">
  <a href="/images/blog/cloud-benchmarks/bounded-snapshot-cycles.svg" title="Open full-size figure"><img src="/images/blog/cloud-benchmarks/bounded-snapshot-cycles.svg" alt="Median user cycles per bounded snapshot iteration: 1,291 originally, 703 after changing the shared acquisition, and 522 after also changing the refund." /></a>
  <figcaption>Each run read 200,000 snapshots of the same four-byte buffer inside a 64-byte actor heap.</figcaption>
</figure>

We rotated the three builds on the same Intel C4 for 16 measured rounds. Every run used one worker and returned 19,700,000. The new acquisition cut user cycles by 45.5%. Applying the refund change to that build cut another 26.0%. Comparing the first and last builds directly gave a 59.6% reduction, with a paired 95% interval of 59.4% to 59.7%. The graph divides whole-process counter readings by 200,000, so the estimates include process startup and shutdown.

We also exercised [the read and write variants of the byte benchmark](https://github.com/hew-lang/hew/blob/ef6b6a79d456f932626ca63641c1a0b44d485c45/examples/benchmarks/calibration/primitives.hew#L37). A million snapshot reads from a 65,536-byte buffer used 14.7% fewer cycles after the acquisition change. In the write variant, each iteration cloned a 64-byte buffer and changed one byte. Its checksum included both the changed byte and the original, so an implementation that wrote through to the original would fail. Over 10,000 writes the acquisition change saved 3.9% of cycles. The write still had to produce a private copy.

## A child that usually finishes straight away

A similar opportunity came up in the code for a coroutine call. The following program calls `advance` 1,048,576 times. Four calls sleep for one millisecond. The rest add one and return immediately.

```hew
fn advance(n: i64) -> i64 {
    if n % 262144 == 262143 { sleep(1ms); }
    n + 1
}

fn main() {
    var sum = 0;
    for n in 0..1048576 { sum += advance(n); }
    println(sum);
}
```

A suspended call needs a frame to hold the values it will use when it resumes. Hew already pools small frames on the worker, so successive calls can reuse an allocated block. Each call still enters the frame manager to acquire a block and returns it on completion.

In this loop the parent waits for each `advance` to finish before starting the next iteration. The compiler knows the child function, and its storage can live inside the parent's frame. When the timer fires, the child resumes using the same storage. Once it returns, the next iteration can use that space again.

<figure class="benchmark-figure">
  <a href="/images/blog/cloud-benchmarks/frames.svg" title="Open full-size figure"><img src="/images/blog/cloud-benchmarks/frames.svg" alt="With separate frames, the parent holds a pointer to a child allocation. With frame reuse, the child occupies a slot inside the parent&#x27;s frame across suspension." /></a>
  <figcaption>While the child sleeps, both frames stay live. After the child returns, the next call can use the same space.</figcaption>
</figure>

### Where the child function went in a backtrace

We tried several ways of giving the child space in its parent. In a local test with 12,000 calls, we counted acquisitions at the entry to Hew's frame manager. The original program made 12,001 acquisitions, one for the parent and one per call. Telling LLVM it could elide the child's allocation cut the count to one. LLVM also inlined the child's startup code into its parent.

That showed up when the child panicked before its first suspension. Hew reported the correct source file and line, but the backtrace had lost the child's function name. The machine code for the small test had grown from 5,076 to 7,605 bytes. We tried reserving a fixed 128-byte slot in the parent and keeping the child's executable body separate. The name came back. The parent then carried all 128 bytes even on a path that never called the child.

<figure class="benchmark-figure">
  <a href="/images/blog/cloud-benchmarks/frame-placement-text.svg" title="Open full-size figure"><img src="/images/blog/cloud-benchmarks/frame-placement-text.svg" alt="Native code size in the local placement experiment. The pool used 5,076 bytes, blanket inlining 7,605 bytes, a fixed child slot 5,565 bytes, and exact-sized placement 5,502 bytes." /></a>
  <figcaption>Compiled code size for four versions of the 12,000-call test, measured in bytes of executable text.</figcaption>
</figure>

In [the merged implementation](https://github.com/hew-lang/hew/pull/4021), LLVM sizes the child's storage for the target. A short startup function enters the named resume function synchronously. An immediate panic can therefore report both the child and its caller. We also cancelled a suspended child in a race and checked that its deferred cleanup ran once and closed its resource once. The placement rule applies to direct, serial child calls in loops. A forked task or an escaping handle can outlive the caller and keeps independent storage.

### What each compiler change saved

Before enabling placement, we [reduced the size of individual frames](https://github.com/hew-lang/hew/pull/4018). Some functions carried tracking slots for children or runtime operations they never started. Removing those slots took a conditional-sleep leaf from 120 to 64 bytes in the local test. On the million-call C4 workload, that first change saved 6.2% of instructions and 1.3% of user cycles.

Placing the child in its parent then cut 61.3% of cycles relative to the smaller-frame build. Across both changes the program used 44.9% fewer instructions and 61.8% fewer cycles. The paired 95% interval for the cycle reduction was 61.8% to 62.1%. The same runtime was linked into each executable. All three printed 549,756,338,176.

<figure class="benchmark-figure">
  <a href="/images/blog/cloud-benchmarks/lifetimes.svg" title="Open full-size figure"><img src="/images/blog/cloud-benchmarks/lifetimes.svg" alt="Reductions from baseline on Intel C4. Shared reads saved 28.7% of instructions and 14.7% of cycles. The bounded actor saved 65.4% and 59.6%. The coroutine loop saved 44.9% and 61.8%." /></a>
  <figcaption>Each percentage compares two builds on the same Intel host. The reference program and unit of work differ across rows.</figcaption>
</figure>

## Running the same source on Arm and Intel

For a separate architecture comparison, we built [Hew revision b8e5ae618880](https://github.com/hew-lang/hew/commit/b8e5ae618880) natively on each machine. This revision predates child-frame placement. We ran a scan of 4,096 vector elements repeated 2,048 times, and a chain of fallible functions called 500,000 times. Each program used one pinned core and produced the same output digest on both machines.

We ran the Arm build on a Neoverse V2 and the Intel build on a Xeon Platinum 8581C.

<div class="benchmark-comparison">
<table class="benchmark-pair">
  <caption>Vector scan · per element</caption>
  <thead><tr><th scope="col">Metric</th><th scope="col">Arm</th><th scope="col">Intel</th></tr></thead>
  <tbody>
    <tr><th scope="row">Time (ns)</th><td>1.108</td><td>0.873</td></tr>
    <tr><th scope="row">User cycles</th><td>2.835</td><td>2.906</td></tr>
    <tr><th scope="row">Instructions</th><td>15.189</td><td>19.227</td></tr>
  </tbody>
</table>

<table class="benchmark-pair">
  <caption>Fallible call chain · per call</caption>
  <thead><tr><th scope="col">Metric</th><th scope="col">Arm</th><th scope="col">Intel</th></tr></thead>
  <tbody>
    <tr><th scope="row">Time (ns)</th><td>210.052</td><td>193.696</td></tr>
    <tr><th scope="row">User cycles</th><td>376.406</td><td>448.942</td></tr>
    <tr><th scope="row">Instructions</th><td>845.889</td><td>811.140</td></tr>
  </tbody>
</table>
</div>

The time in each table is the median of seven process timings, including startup. We collected the hardware counters in separate runs. Arm used fewer user cycles per operation on both workloads. Intel finished both sooner. Core frequency and time spent outside user mode also affect a process timing.

On the day of the test, the eight-vCPU Spot machines cost US$0.057808 for Arm in the Netherlands and US$0.10123 for Intel in Dallas per hour. At those rates, an hour of Intel vector scans cost about 10.1 cents. Extrapolating the single-core measurements, the same work would take about 76 minutes on Arm and cost 7.3 cents. For the fallible call chain, the corresponding Arm figures were about 65 minutes and 6.3 cents. Those estimates charge the whole VM for the time occupied by one worker. A service keeping all cores busy would need its own throughput measurement.

## Energy per operation and per instruction

The cloud runs gave us time per call and instructions per call. With power as the unknown, we can calculate the reading at which the machines would use equal energy. A watt is one joule per second, so multiplying average watts by nanoseconds per call gives nanojoules per call.

Take the vector scan. Intel took 0.873 ns per element and Arm took 1.108 ns. Divide the first time by the second and you get 0.788. If the Arm machine drew 78.8% as much average power as the Intel machine during these runs, both would spend the same energy per element. The fallible call took 193.696 ns on Intel and 210.052 ns on Arm. There the two would break even at 92.2% of Intel's power.

<figure class="benchmark-figure">
  <a href="/images/blog/cloud-benchmarks/energy-break-even.svg" title="Open full-size figure"><img src="/images/blog/cloud-benchmarks/energy-break-even.svg" alt="Calculated energy per operation as a function of assumed Arm power relative to Intel. Energy is equal at 78.8% of Intel power for the vector scan and 92.2% for the call chain." /></a>
  <figcaption>At the horizontal line, both machines would spend the same joules on one operation. The horizontal axis varies the assumed power ratio.</figcaption>
</figure>

At an assumed power ratio of 85%, between the two crossings in the figure, Arm would spend about **8% more energy per vector element** and **8% less per call**.

We can do the calculation per retired instruction, too. The Arm scan retired 15.189 user instructions per element. Dividing 1.108 ns by that count gives 0.0729 ns per instruction. Multiplying by the measured watts would give nanojoules per retired user instruction. The Intel coefficient is 0.0454. The [seven rounds of timing and counter data (CSV)](/images/blog/cloud-benchmarks/native-samples.csv) include the operation count for each program. Each round timed one execution and collected user-mode counters in another. For a compiler change on either machine, joules per element would tell us whether scanning the same vector got cheaper, even if the compiler changed the number of instructions in the loop.

To measure that on hardware, we'd repeat the scan on a dedicated server long enough to collect a series of wall-power samples. We'd integrate watts over the timed interval and divide the resulting joules by the number of elements scanned. Dividing the same joules by the retired user instructions counted during that interval would give us the energy per instruction. Measuring the server at idle would let us report both the energy drawn at the outlet and the extra energy the scan used above idle. Grid'5000 documents servers with external meters that can sample up to 50 times a second. [Grid'5000 energy measurement tutorial](https://www.grid5000.fr/w/Energy_consumption_monitoring_tutorial)
