Designer scripts run a per-entity update that calls into the engine thousands of times a frame and blows the budget; what does each scripting boundary crossing cost, and how do you fix it?
answer
- count the crossings first
- marshalling, lookups, allocations
- coarse calls over chatty ones
- events instead of polling
- hot loops stay native
basics
~20 sEach crossing between script and engine pays for lookup, argument conversion, type and handle checks and often a temporary allocation. Fix it by crossing less: event-driven scripts, batched coarse-grained calls, cached lookups and hot loops moved into native code.
solid answer
~50 sA call from an embedded scripting language into native engine code is far more expensive than a native call. The binding layer looks up the function, **marshals** each argument between the script's value representation and the engine's, checks types, resolves object **handles** to check the target is still alive, and often **allocates**: a boxed vector, a converted string, a temporary table, which also feeds the script's garbage collector. Neither side can inline across the boundary. Thousands of small crossings per frame add up, so first **measure** crossings per frame and time spent in the binding layer. Then cross less: make scripts **react to events** instead of polling every frame, expose **coarse-grained** functions that do the work natively for many entities in one call, cache function references and intern strings to IDs at load, avoid per-call allocations, and tick distant or idle scripts less often.
go deeper
Know that calling engine code from a script is much slower than a normal function call, and that per-frame script work adds up.
Name the parts of a crossing: dispatch, argument marshalling, type checks, handle resolution and allocations that create garbage.
Diagnose by counting crossings per frame, then fix with events instead of polling, batched native calls, cached lookups and reduced tick rates.
Set the split between a small fast native API and a broad scripting surface, and enforce a script budget that tools report per frame.
## The scenario Designers script quests and gameplay in an embedded scripting language so they can iterate without rebuilding the engine. Early on every entity's script has an `update(dt)` function, and inside it calls such as `get_position(self)`, `distance_to(player)`, `play_sound("step")`. With a couple of thousand scripted entities each making a handful of engine calls, a frame makes ten thousand or more crossings. Suppose, as a scenario figure, each round trip costs half a microsecond: 10,000 crossings cost 5 ms, a large share of a frame before any real work is done. ## What one crossing costs A call from script into the engine passes through a **binding layer**, generated or hand-written glue that translates between two worlds. Its costs, in roughly the order they occur: - **Dispatch**: finding the native function, often through a name lookup or a table, if the reference was not cached. - **Marshalling**: converting each argument from the script's representation to the engine's and the result back. Numbers are cheap; strings may be copied or re-encoded; vectors and structs may be unpacked field by field. - **Checks**: verifying argument types and counts, because a script can pass anything. - **Object lifetime**: scripts should hold **handles** to engine objects, not raw pointers, so each call resolves the handle and checks it is still alive. - **Allocation**: returning a vector or string often creates a new script-side object. In a garbage-collected scripting layer that is per-frame garbage, which later costs a collection pause; keeping those pauses out of the frame is a memory-budget concern of its own. - **Lost optimisation**: neither the script compiler nor the native compiler can see across the boundary, so nothing is inlined or hoisted. Script code itself is usually slower than native code, but the crossing overhead is what multiplies with chatty call patterns. ## Diagnosing it 1. Instrument the binding layer to **count crossings per frame**, broken down by function and by script. 2. Profile how frame time splits between script execution, the binding layer and native work. 3. Look for the usual culprits: per-frame polling of state that rarely changes, the same lookup repeated every frame, strings passed as identifiers, and functions that return fresh objects. ## Fixing it | Pattern | Before | After | |---|---|---| | Polling | Every quest script checks `is_door_open` every frame | The script subscribes to a `DoorOpened` event and runs once | | Chatty calls | Script loops over 200 enemies calling `distance_to` each | One native call returns the enemies within a radius | | Strings as IDs | `play_sound("step")` hashes or looks up a string per call | The sound ID is resolved once at load and passed as a number | | Repeated lookups | Function found by name each call | Reference cached when the script loads | | Fresh objects | `get_position` returns a new vector object | Values returned as plain numbers or written into a reused buffer | | Everything ticks | Every scripted entity updates every frame | Idle or distant scripts tick less often or sleep until an event | The principle behind all of them: **scripts orchestrate, native code iterates.** A script decides that a squad should flee; a native system moves two hundred units. ## The trade-off Coarse-grained, batched APIs are faster but less flexible: each one is a feature a programmer must build, and designers lose some freedom to compose small primitives. Teams usually keep a small, fast native surface for hot paths and a broader, slower surface for one-off quest logic, and they publish a per-frame **script budget** that tools report against, so a slow script is caught in a playtest rather than in a certification run.
- Why should scripts hold handles to engine objects rather than raw pointers?Engine objects are destroyed on the engine's schedule, not the script's. A handle with a generation count can be checked on each call and fail cleanly, with an error the designer can see, while a raw pointer kept by a script would crash or corrupt memory once the object is gone.
- How can a script that only reads engine state still create garbage every frame?Any binding that returns a composite value, such as a vector, a string or a list, may build a new script-side object for it on every call. Reading a position in every update for thousands of entities produces thousands of short-lived objects per frame, which a collector must eventually reclaim.
- A script-to-engine call costs the same as a native call
- The fix is always to rewrite the scripting language's interpreter
- Every scripted entity should poll the world each frame
- Passing strings as identifiers across the boundary is free
- Scripts can safely cache raw pointers to engine objects