Skip to main content

Building Pico, the world's fastest signals library

Robert Balicki

Pico documentation ⋄ Benchmark results ⋄ Demos

Introducing Pico. A cartoon farmer says “It’s fast!”

It is a trite observation that, while hardware continues getting faster, user-facing applications remain slow. Are lazy developers to blame? High-level frameworks? Cold, hard economics? Higher standards? Whatever the ultimate cause, the mechanism is the same: our applications run more code than is necessary. Applications aren't snappy because they use some fancy new algorithm. They're fast when they avoid doing unnecessary work.

Consider a multiplayer game, where a server sends an updated { name, latestLocation } record every second. The location changes frequently, but the name does not. Should a component that reads only the name re-render every second? Clearly not. Yet the default is often to subscribe to the whole record and re-render on every update.

A signals library lets the component subscribe to just the part it cares about. Store the record in a source called user, then define a derived node called name that reads user.name. When a new record arrives, the signals library can rerun the one-line function, compare the results, and skip re-rendering the component. If a thousand components read the same name, they can all share that calculation.

The final function reads the name projection. The projection reads the user record.

How elegant! Unfortunately, there's a cost to figuring out which work you can skip. The library has to remember what each computation read, which computations depend on that result, and whether its cached value is still current. If re-rendering the name takes less time than tracking all of those dependencies, you've made the application slower. How quickly the library can perform that bookkeeping matters.

I wanted a signals library for the next version of Isograph, so I built Pico. I designed the API, decided on the contracts the user must uphold, and reviewed the code. A succession of coding agents wrote the implementation, profiled it, and kept trying changes against the benchmarks.

Across 57 workloads comparing 15 signals libraries, Pico had the fastest median time on 35. See the full benchmark results and four whimsical performance demos.

Why Isograph needs Pico​

Isograph is a compiler-driven framework for building data-driven applications that are performant and stable right out of the box. In Isograph, the basic building blocks are client fields, which are functions from some graph data to an arbitrary value, written using the iso function:

export const fullName = iso(`
field User.fullName {
firstName
lastName
}
`)(({ data }) => data.firstName + ' ' + data.lastName);

You can think of User.fullName as a derived node.

Client fields can depend on each other:

export const address = iso(`
field User.formattedAddress {
fullName
streetAddress
}
`)(({ data }) => data.fullName + '\n' + data.streetAddress);

In the current version of Isograph, whenever any input that flows into User.formattedAddress (firstName, lastName, and whatever flowed into streetAddress) changes, the entire function is re-executed. We can cache more aggressively!

Rather than designing an integrated caching system, I decided to extract it as a separate library, which can not only power Isograph, but also be incorporated into other projects.

How Pico performs​

Across 57 workloads comparing 15 signals libraries, Pico had the fastest median time on 35, placed second on 11, and third on six. Full benchmark results.

Three cases give a feel for where Pico does especially well:

  • Many readers of one field. In the { name, latestLocation } example, 1,000 components display the same name. Similarly, the benchmark alternated between updating one unread field and rerendering one randomly chosen component. The median event took 2.75 µs in Pico, 21.0 µs in Alien, and 19.4 µs in Preact.
  • Switching views over cached data. Two screens can reuse the same computed values. Switching between a list and a board over cached records, including cleanup after each switch, took 0.39 ms in Pico, 3.41 ms in Alien and 0.51 ms in Preact.
  • Repeated writes in a batch. When the same source is updated 10,000 times in a batch, readers only need the final value. Across the native API runs, Pico took 30% less time than Alien, 48% less than Preact, and 36% less than r3.

How Pico was written​

Pico is an experiment in agentic hill climbing. I didn't write any code, though I reviewed it. I designed the user-facing API and set the goals, contracts, and acceptance criteria. I suggested experiments and acted as a cheerleader.

The models (Neon High, Astra 6.2 High, and Opus 5.5 High) implemented the library, wrote tests, proposed hypotheses, profiled the code, and fixed regressions.

An existing reactivity benchmark suite served as the agents' starting point, and they ran and extended it repeatedly. Two questions came up early: which engine operations did the original suite leave untested, and did it adequately test "realistic" workloads?

The usual sequence (according to Astra 6.2 High) was to establish a baseline, profile a real workload, test one change in isolation, then combine the winners and run the full suite on the PR build. A confirmed slowdown sent the changes back for diagnosis or removal.

For the most part, I used one main agent at a time (it could employ subagents), and 99% of the library was done in a week.

I reran seven workloads on 108 revisions of Pico using Node 24.12.0 on an Apple M5 Pro. By the end of the first day, their geometric mean throughput had reached 4.71× the prototype’s. It finished at 4.38×. Summing a 32-way diamond gained another 16% after day one, while cached reads lost 47%.

I also measured subscriptions and batches on the 99 revisions that supported them. The last two changes raised throughput for 256 writes in one batch by 1.70× and then another 1.40×. Even after those gains, the batch ran at 56% of the first compatible revision’s throughput.

Throughput by revision for nine Pico workloads. The first seven run on all 108 source revisions. Batching and subscriptions start at the tenth.

Retrospective on the process​

The overall workflow worked well (subjectively), perhaps because Pico is the perfect target library for agentic hill climbing. The API is small. There was a pre-existing benchmark. Correct behavior is easy to determine (the agents got it wrong a few times, but it didn't take much clarification), so a comprehensive test suite is feasible. The agents could draw on a large body of ideas from the literature.

The number one thing that slowed the process down was the fact that I was too lazy to connect AWS, and thus give the agents a predictable benchmarking environment. So instead, I ran one benchmark at a time on my machine.

In addition, in the middle of the week, I discovered that the benchmarking process was broken: the setup was running the same variant first. Some first runs were unusually slow, so I could no longer trust comparisons that used that ordering. So, the agent spent an entire day rerunning benchmarks and questioning prior decisions. Wasteful!

Could the overall process have gone better? Did I get driven into swearing at the agents? Yes. Did the agents waste stupid amounts of tokens and need to be reminded to be efficient? Yes. But I am happy with the result.

What was tried that didn't pan out​

Because agents did much of the work, I was able to prototype and try many different variations. Many didn't work out. The top two:

WebAssembly​

Most of Pico's bookkeeping involves walking a graph and updating the edges between nodes. It seems like a good candidate for WebAssembly. I had the agents build a prototype that kept the graph in WebAssembly and kept application values and user-written functions in JavaScript.

The most promising result came from when 1,000 components read the same unchanged name. The WebAssembly version took 64% less time per update. But as it turns out, the WebAssembly version took a shortcut that could also be incorporated on the JavaScript side: it skipped visiting all 1,000 readers when the shared projection stayed unchanged. When that shortcut was integrated on the JavaScript side, it cut the time per update there by 92%.

Ultimately, across 21 app-like workloads, the WebAssembly version was slower on 16, so I kept Pico in JavaScript. I still think a WebAssembly implementation can work! But it didn't pan out for the initial version.

Scheduling by height​

Suppose 1,000 components display the same player’s nameplate. The nameplate shows Sam · safe while Sam is inside a safe zone and Sam outside it. When Sam moves within the safe zone, the server sends a new player record with an updated latestLocation. Pico marks all 1,000 components as possibly dirty before it recomputes the nameplate. The nameplate still says Sam · safe, so none of the components needs to rerender.

One alternative is to re-execute the projection function eagerly, and if the result of the projection function is unchanged, avoid visiting the 1,000 components.

But suppose the nameplate also reads a derived value called status, which can depend on user.latestLocation (the status might change if the user is in a safe zone). If Pico reruns the projection while still marking the graph, status may not have been updated yet, so it can still be marked CLEAN. If Pico immediately re-executes the projection (required to avoid visiting the 1,000 components), the projection will either encounter an inconsistent state (i.e. an outdated, inaccurate status) or have to not trust the CLEAN flag and re-validate status anyway.

Scheduling by height is one way to ensure that status always runs first. status is lower-height, and lower-height nodes are executed first. The projection can then use the current value of status without worry. If the projected name stays the same, propagation stops before the 1,000 renders.

This helped when many components read a field that rarely changed (as in the name example). But, this didn’t produce consistent wins overall, probably because it was too costly to maintain the heights in order and update heights when different invocations read different fields.

(Dependencies can change: executing function x() { return a.read() ? b.read() : c.read() } when a is true informs Pico that x has a greater height than a and b. But it won't know that x has a greater height than c. So it's not so easy!)

r3 is trying out this approach, and is a very promising project.

How Pico is so damn performant​

Nobody should write code this hideous:

if ((node.traversalFlags & MARKED_BEYOND) !== NO_FLAGS) {
node.traversalFlags &= ~MARKED_BEYOND;
if (node.callbackState === HAS_CALLBACK) {
queue = queueNodeWithCallback(queue, node);
} else if (node.firstDependent !== undefined) {
if (firstLazyBranch !== undefined) {
(pendingLazyBranches ??= []).push(firstLazyBranch);
}
firstLazyBranch = node;
}
}

But hey, it works, and you can't argue with benchmarked results. (I mean, you can, but hopefully the benchmarks hold up!)

Looking back, the following principles were identified by the agent as generally leading to more performant code. I wouldn't recommend always adopting all of these (as they substantially worsen the DevEx), but for core primitives, they may be justified:

Measuring performance​

  • Benchmark each optimization against the code it replaces. Some changes that appear likely to be wins will not turn out to be so!
  • Compare data structures on the mix of operations your application performs. Pico keeps a linked list of each node’s readers. We tried an array that removed a reader by moving the last entry into its slot. With the array, reading a small part of a large graph took 63% less time, but changing the order in which a computation read its inputs took 34–68% longer. We kept the linked list because the array slowed five application workloads by about 4–9%.
  • Measure memory use and speed separately. A smaller representation can take more work to update. In Pico, one change saved 56 bytes when the first listener attached but made replacing a listener 10.8% slower.

Avoiding allocations​

  • Avoid rebuilding a data structure on every pass. If most entries survive from one pass to the next, walk the existing structure and update the entries that changed. Pico does this with dependency lists. A computation that reads the same inputs in the same order can reuse every edge.
  • Avoid allocating closures. If every object gets its own set closure, creating 10,000 objects also creates 10,000 functions. Define set on the prototype or use a top-level set(object, value) so all the objects share one function.
  • Choose a less ergonomic API when the convenience would require an allocation on every call. A tuple makes const [handle, dispose] = acquire() convenient to write. In JavaScript, that tuple is an array, and the disposer is another allocation if it closes over the handle. Pico returns just the handle. The caller has to keep it and call releaseRetain(handle) when the resource is no longer needed, but acquiring it needs neither the array nor the disposer closure.

Avoiding unnecessary mutation​

  • Avoid clearing an already-empty array. If a reusable queue is often empty at cleanup time, test whether it has any items before setting queue.length = 0. In Pico’s one-source, one-reader benchmark, that guard cut the time per update from about 37 ns to 22.5 ns.
  • Passing a frequently changing value as an argument can be faster than keeping it in a global. A global current computation makes read(source) convenient, but each nested computation has to save the old value, install its own, and restore the old one on return. Pico exposes readSource(callingNode, source), so the caller has to pass the extra argument on every tracked read. In a benchmark that reread 1,000 derived values, the global version took 4.7% longer.
  • Skip stack entries when the data already records the return path. For example, when descending a tree with parent pointers, you can walk back up through those pointers. A graph with multiple parents may still need a stack entry to remember which edge you followed.

Object shapes​

  • Keep the object layout stable when an object changes state. A discriminated union could express which fields exist in each state, but our implementation would have to allocate a differently shaped object on each transition. Pico therefore uses a "merged" representation, which performs better but allows us to represent impossible states, and we must be careful to enforce those invariants.
  • Avoid polymorphism. Duplicate a hot function when callers would otherwise pass it objects with different shapes. Pico has two identical functions, one for linking a reader to a source node and another for linking a reader to a derived node. V8 optimizes each helper’s field access for a single object shape, so the optimized code reads the field at a fixed offset.

Avoiding redundant checks​

  • Don’t repeat a check the caller already made. Suppose drain(queue) checks whether the queue is empty. Put the actual work in drainNonempty(queue) and let drain call it after the check. A caller that just pushed an item can go straight to drainNonempty. The article Push ifs up and fors down makes this point much more elegantly than I ever could.
  • Move a check outside the loop when its result holds for every iteration. Suppose a flag selects whether to copy or transform a batch of records. Check the flag once per batch, then run either the copy loop or the transform loop. That saves one branch per record.

API tradeoffs​

  • Keep only the work required for correctness in the core library. Let callers opt into everything else. For example, Pico requires a computation to return normally. If a computation can throw, its author can catch the exception inside that computation and choose a fallback. Pico can call every other computation directly.
  • Let callers enforce invariants that would otherwise require a check on every read. Pico requires computations to be pure and synchronous and the dependency graph to be acyclic. If A reads B and B reads A, the first read can overflow the stack. A caller who wants an earlier error can wrap computations with a check for re-entry. Everyone else can evaluate a computation without maintaining or checking that extra state.

Conclusion​

Toward the end of the week, I asked the agent what was innovative about Pico. It said "nothing." Every technique we used had precedent in some other library or in the literature. "It's in the convex hull, meatbag, now go back to the salt mines!" I was a little miffed, needless to say.

But on reflection, the answer is encouraging. I knew what I wanted from a signals library and which workloads mattered for Isograph. I had no particular expertise writing blazing fast JavaScript. I would not have guessed that checking whether an array was empty before setting its length to zero would improve performance. But agents have time on their hands, and they dutifully tried many different combinations, slowly accruing performance gains. There are many other libraries out there, similarly waiting to be hill climbed, by someone with some time to kill over the holidays!