From 7c01583ef7b623196be853aa32f42f4305cce550 Mon Sep 17 00:00:00 2001 From: Michiel Borkent Date: Wed, 25 Nov 2026 15:56:06 +0100 Subject: [PATCH 1/3] Document the cost of creating a callback --- API.md | 55 +++++++++++++++++++++++-------------------- doc/guide.md | 17 +++++++++++++ src/babashka/ffi.clj | 3 +++ src/babashka/ffi.cljs | 3 +++ 4 files changed, 52 insertions(+), 26 deletions(-) diff --git a/API.md b/API.md index 8f35426..a3f36a5 100644 --- a/API.md +++ b/API.md @@ -137,7 +137,7 @@ Returns the native address of pointer p as a Clojure long. Function. Returns the alignment, in bytes, of type keyword t or of a struct layout. -

Source

+

Source

## `alloc` ``` clojure @@ -160,7 +160,7 @@ result with the matching C deallocator. CAUTION: Do not close the arena while C uses its memory. C can access released memory. -

Source

+

Source

## `auto-arena` ``` clojure @@ -170,7 +170,7 @@ Function. Returns an arena that the garbage collector manages. Keep the arena reachable while C uses its pointers. You cannot close it. -

Source

+

Source

## `byte-buffer` ``` clojure @@ -186,7 +186,7 @@ invalid memory access can stop the process. The byte order is big-endian, as it is for each new ByteBuffer. If you need a different byte order, set it with .order. -

Source

+

Source

## `callback` ``` clojure @@ -216,9 +216,12 @@ An automatic arena releases the pointer once the pointer itself becomes unreachable. The garbage collector cannot see the copy that C holds. Use an automatic arena only when your reference outlives every call that C can make. +Creating a callback takes microseconds. Create it once and reuse it across +C calls. + CAUTION: Unregister the callback before its arena releases the pointer. Catch exceptions inside f. An uncaught exception can stop the process. -

Source

+

Source

## `cfn` ``` clojure @@ -244,7 +247,7 @@ create the binding before you load its library. A :& in argtypes declares a variadic C function. The types before :& are the fixed parameters. Types after :& declare the variadic argument types. With no types after :&, each call infers them from its values. -

Source

+

Source

## `clone` ``` clojure @@ -254,7 +257,7 @@ Function. Allocates a copy of pointer src in arena with the same size and returns the new pointer. Use reinterpret to specify a size for pointers from C. -

Source

+

Source

## `confined-arena` ``` clojure @@ -264,7 +267,7 @@ Function. Returns an arena for one thread. Create this arena in with-open to release its memory. -

Source

+

Source

## `copy` ``` clojure @@ -283,7 +286,7 @@ middle of dst, slice it first: (ffi/copy src (ffi/slice dst 16) n) Supports overlapping regions, as with memmove. -

Source

+

Source

## `defcfn` ``` clojure @@ -336,7 +339,7 @@ The wrapper can have multiple arities. Its argument lists can differ from the C function. The raw name does not enter the namespace. The wrapper form needs a literal argtypes vector. Only the plain form accepts an argtypes expression. -

Source

+

Source

## `find-symbol` ``` clojure @@ -350,7 +353,7 @@ Finds sym and returns a pointer to it. Returns nil for an unknown symbol. A library value limits the search to one library and its dependencies. Without a library value, find-symbol searches all loaded libraries. Then it searches the default system lookup. -

Source

+

Source

## `global-arena` ``` clojure @@ -360,7 +363,7 @@ Function. Returns the global arena. Its memory exists until the process stops. You cannot close this arena. -

Source

+

Source

## `load-library` ``` clojure @@ -385,7 +388,7 @@ map uses the keys :mac, :linux, and :windows: common installation directories. Returns a library map whose :path value identifies the loaded candidate. The map can be the first argument to cfn. In that form, cfn searches this library and its dependencies. -

Source

+

Source

## `load-system-library` ``` clojure @@ -396,7 +399,7 @@ Function. Loads a shared library by its short name. For example, "z" selects libz.dylib, libz.so, or z.dll. On Linux, the search also includes versioned names such as libz.so.1. Returns the same library map as load-library. -

Source

+

Source

## `null` @@ -404,7 +407,7 @@ names such as libz.so.1. Returns the same library map as load-library. The NULL pointer. -

Source

+

Source

## `null?` ``` clojure @@ -413,7 +416,7 @@ The NULL pointer. Function. Returns true for a NULL pointer. Returns false for all other pointers. -

Source

+

Source

## `place` ``` clojure @@ -437,7 +440,7 @@ as a vector, a union as a pointer on read and a pair on write. A path to a union member accepts the member's value directly on write. Throws for an invalid path. Create a place once and reuse it. -

Source

+

Source

## `pointer?` ``` clojure @@ -482,7 +485,7 @@ specifies the layout member's type and offset. Checks the access against the size of p. Rejects a zero-size pointer. reinterpret specifies a valid size. -

Source

+

Source

## `read-array` ``` clojure @@ -503,7 +506,7 @@ read with [:array :pointer n]. For an array of structs, or for elements decoded the way read decodes them, use read with an [:array t n] layout. -

Source

+

Source

## `reinterpret` ``` clojure @@ -550,7 +553,7 @@ Function. Returns an arena for multiple threads. Create this arena in with-open to release its memory. -

Source

+

Source

## `size` ``` clojure @@ -570,7 +573,7 @@ Function. Returns the size of a type keyword or struct layout, in bytes. The size of a struct includes padding. -

Source

+

Source

## `slice` ``` clojure @@ -597,7 +600,7 @@ Function. Copies s into arena as a NUL-terminated UTF-8 string and returns its pointer. The arena controls the lifetime of the string. -

Source

+

Source

## `with-open` ``` clojure @@ -610,7 +613,7 @@ value in reverse order when body returns or throws. CAUTION: On Node.js the arena closes when body returns. Do not return a promise that still uses it. -

Source

+

Source

## `write` ``` clojure @@ -626,7 +629,7 @@ selects a union member, pass the member's value directly. Checks the access against the size of p. Rejects a zero-size pointer. reinterpret specifies a valid size. -

Source

+

Source

## `write-array` ``` clojure @@ -641,7 +644,7 @@ Copies Java array arr into memory at pointer p, at byte offset (default Copies raw bytes without converting elements. arr must be a Java array of the matching type: an int[] for :int, a long[] for :long or :pointer, a byte[] for :char. -

Source

+

Source

## `write-string` ``` clojure @@ -657,4 +660,4 @@ The write takes the UTF-8 byte count of s plus one byte. (alength (.getBytes s "UTF-8")) is that byte count without the NUL. Checks the write against the size of p. Rejects a zero-size pointer. reinterpret specifies a valid size. -

Source

+

Source

diff --git a/doc/guide.md b/doc/guide.md index af31730..e548033 100644 --- a/doc/guide.md +++ b/doc/guide.md @@ -1154,6 +1154,23 @@ per iteration. ### Callbacks +Creating a callback costs about 8 us on the JVM, 2 to 4 us in a babashka +build with libffi and 2 us on Node.js. For a callback that you pass to C on each of many calls, +create it once and reuse it: + +```clojure +(def int-comparator + (ffi/callback (ffi/global-arena) + (fn [l r] + (compare (ffi/read (ffi/reinterpret l 4) :int) + (ffi/read (ffi/reinterpret r 4) :int))) + [:pointer :pointer] :int)) + +(qsort values 5 4 int-comparator) +``` + +A reused callback must not close over the state of one call. + In a build with libffi, every callback goes through libffi, and an empty callback costs about 30 ns. In a build without libffi, a native image registers these callback shapes when it is built, and a callback costs about diff --git a/src/babashka/ffi.clj b/src/babashka/ffi.clj index 8e0498c..45700fb 100644 --- a/src/babashka/ffi.clj +++ b/src/babashka/ffi.clj @@ -2779,6 +2779,9 @@ unreachable. The garbage collector cannot see the copy that C holds. Use an automatic arena only when your reference outlives every call that C can make. + Creating a callback takes microseconds. Create it once and reuse it across + C calls. + CAUTION: Unregister the callback before its arena releases the pointer. Catch exceptions inside f. An uncaught exception can stop the process." [arena f argtypes rettype] diff --git a/src/babashka/ffi.cljs b/src/babashka/ffi.cljs index ad86861..319a267 100644 --- a/src/babashka/ffi.cljs +++ b/src/babashka/ffi.cljs @@ -1385,6 +1385,9 @@ it once the pointer itself becomes unreachable. The garbage collector cannot see the copy that C holds. + Creating a callback takes microseconds. Create it once and reuse it across + C calls. + CAUTION: Unregister the callback before its arena releases the pointer." [^Arena arena f argtypes rettype] (when (or (vector? rettype) (some vector? argtypes)) From f323a1506a8a05c02241f7c35e6baf16818f899d Mon Sep 17 00:00:00 2001 From: Michiel Borkent Date: Wed, 25 Nov 2026 15:57:31 +0100 Subject: [PATCH 2/3] Name the ways to reuse a callback with per-call state --- API.md | 4 ++-- doc/guide.md | 28 +++++++++++++++++++++++++--- src/babashka/ffi.clj | 4 ++-- src/babashka/ffi.cljs | 4 ++-- 4 files changed, 31 insertions(+), 9 deletions(-) diff --git a/API.md b/API.md index a3f36a5..90d4386 100644 --- a/API.md +++ b/API.md @@ -216,8 +216,8 @@ An automatic arena releases the pointer once the pointer itself becomes unreachable. The garbage collector cannot see the copy that C holds. Use an automatic arena only when your reference outlives every call that C can make. -Creating a callback takes microseconds. Create it once and reuse it across -C calls. +Creating a callback takes microseconds. For a callback that C calls on each +of many calls, and that needs no per-call state, create it once and reuse it. CAUTION: Unregister the callback before its arena releases the pointer. Catch exceptions inside f. An uncaught exception can stop the process. diff --git a/doc/guide.md b/doc/guide.md index e548033..f36975e 100644 --- a/doc/guide.md +++ b/doc/guide.md @@ -1155,8 +1155,8 @@ per iteration. ### Callbacks Creating a callback costs about 8 us on the JVM, 2 to 4 us in a babashka -build with libffi and 2 us on Node.js. For a callback that you pass to C on each of many calls, -create it once and reuse it: +build with libffi and 2 us on Node.js. For a callback that C calls on each of +many calls, and that needs no per-call state, create it once and reuse it: ```clojure (def int-comparator @@ -1169,7 +1169,29 @@ create it once and reuse it: (qsort values 5 4 int-comparator) ``` -A reused callback must not close over the state of one call. +If the C function takes a `user_data` pointer, pass per-call state through it. + +If C calls back on your thread before the call returns, bind a dynamic var +around the call: + +```clojure +(def ^:dynamic *calls* nil) + +(def counting-comparator + (ffi/callback (ffi/global-arena) + (fn [l r] + (vswap! *calls* inc) + (compare (ffi/read (ffi/reinterpret l 4) :int) + (ffi/read (ffi/reinterpret r 4) :int))) + [:pointer :pointer] :int)) + +(binding [*calls* (volatile! 0)] + (qsort values 5 4 counting-comparator) + @*calls*) +;;=> 9 +``` + +Otherwise, create a callback for each object that C calls back for. In a build with libffi, every callback goes through libffi, and an empty callback costs about 30 ns. In a build without libffi, a native image diff --git a/src/babashka/ffi.clj b/src/babashka/ffi.clj index 45700fb..e8a04dc 100644 --- a/src/babashka/ffi.clj +++ b/src/babashka/ffi.clj @@ -2779,8 +2779,8 @@ unreachable. The garbage collector cannot see the copy that C holds. Use an automatic arena only when your reference outlives every call that C can make. - Creating a callback takes microseconds. Create it once and reuse it across - C calls. + Creating a callback takes microseconds. For a callback that C calls on each + of many calls, and that needs no per-call state, create it once and reuse it. CAUTION: Unregister the callback before its arena releases the pointer. Catch exceptions inside f. An uncaught exception can stop the process." diff --git a/src/babashka/ffi.cljs b/src/babashka/ffi.cljs index 319a267..4876a26 100644 --- a/src/babashka/ffi.cljs +++ b/src/babashka/ffi.cljs @@ -1385,8 +1385,8 @@ it once the pointer itself becomes unreachable. The garbage collector cannot see the copy that C holds. - Creating a callback takes microseconds. Create it once and reuse it across - C calls. + Creating a callback takes microseconds. For a callback that C calls on each + of many calls, and that needs no per-call state, create it once and reuse it. CAUTION: Unregister the callback before its arena releases the pointer." [^Arena arena f argtypes rettype] From 35668a18f5a44fc59a3ca07e323e4936b3a1c655 Mon Sep 17 00:00:00 2001 From: Michiel Borkent Date: Thu, 26 Nov 2026 14:50:03 +0100 Subject: [PATCH 3/3] Shorten the callback reuse advice --- API.md | 7 ++++--- doc/guide.md | 33 +++++---------------------------- src/babashka/ffi.clj | 5 +++-- src/babashka/ffi.cljs | 5 +++-- 4 files changed, 15 insertions(+), 35 deletions(-) diff --git a/API.md b/API.md index 90d4386..d22e111 100644 --- a/API.md +++ b/API.md @@ -216,12 +216,13 @@ An automatic arena releases the pointer once the pointer itself becomes unreachable. The garbage collector cannot see the copy that C holds. Use an automatic arena only when your reference outlives every call that C can make. -Creating a callback takes microseconds. For a callback that C calls on each -of many calls, and that needs no per-call state, create it once and reuse it. +Creating a callback is not free in terms of performance, it takes about 8 us +on the JVM and 2 to 4 us in babashka. In performance sensitive code, when +possible, re-use a callback rather than creating it for every invocation. CAUTION: Unregister the callback before its arena releases the pointer. Catch exceptions inside f. An uncaught exception can stop the process. -

Source

+

Source

## `cfn` ``` clojure diff --git a/doc/guide.md b/doc/guide.md index f36975e..8efe535 100644 --- a/doc/guide.md +++ b/doc/guide.md @@ -1154,9 +1154,10 @@ per iteration. ### Callbacks -Creating a callback costs about 8 us on the JVM, 2 to 4 us in a babashka -build with libffi and 2 us on Node.js. For a callback that C calls on each of -many calls, and that needs no per-call state, create it once and reuse it: +Creating a callback is not free in terms of performance, it takes about 8 us +on the JVM, 2 to 4 us in babashka and 2 us on Node.js. In performance +sensitive code, when possible, re-use a callback rather than creating it for +every invocation: ```clojure (def int-comparator @@ -1169,30 +1170,6 @@ many calls, and that needs no per-call state, create it once and reuse it: (qsort values 5 4 int-comparator) ``` -If the C function takes a `user_data` pointer, pass per-call state through it. - -If C calls back on your thread before the call returns, bind a dynamic var -around the call: - -```clojure -(def ^:dynamic *calls* nil) - -(def counting-comparator - (ffi/callback (ffi/global-arena) - (fn [l r] - (vswap! *calls* inc) - (compare (ffi/read (ffi/reinterpret l 4) :int) - (ffi/read (ffi/reinterpret r 4) :int))) - [:pointer :pointer] :int)) - -(binding [*calls* (volatile! 0)] - (qsort values 5 4 counting-comparator) - @*calls*) -;;=> 9 -``` - -Otherwise, create a callback for each object that C calls back for. - In a build with libffi, every callback goes through libffi, and an empty callback costs about 30 ns. In a build without libffi, a native image registers these callback shapes when it is built, and a callback costs about @@ -1228,7 +1205,7 @@ The library includes call trampolines and reachability metadata. For a git dependency, use the sources in the library checkout under `~/.gitlibs`. For a Maven dependency, first extract the sources from the jar: - ```sh +```sh unzip -o "$(clojure -Spath -A:native | tr ':' '\n' | grep 'ffi-.*\.jar')" \ 'babashka/ffi/impl/*.java' -d src-java ``` diff --git a/src/babashka/ffi.clj b/src/babashka/ffi.clj index e8a04dc..38dc6e3 100644 --- a/src/babashka/ffi.clj +++ b/src/babashka/ffi.clj @@ -2779,8 +2779,9 @@ unreachable. The garbage collector cannot see the copy that C holds. Use an automatic arena only when your reference outlives every call that C can make. - Creating a callback takes microseconds. For a callback that C calls on each - of many calls, and that needs no per-call state, create it once and reuse it. + Creating a callback is not free in terms of performance, it takes about 8 us + on the JVM and 2 to 4 us in babashka. In performance sensitive code, when + possible, re-use a callback rather than creating it for every invocation. CAUTION: Unregister the callback before its arena releases the pointer. Catch exceptions inside f. An uncaught exception can stop the process." diff --git a/src/babashka/ffi.cljs b/src/babashka/ffi.cljs index 4876a26..843b192 100644 --- a/src/babashka/ffi.cljs +++ b/src/babashka/ffi.cljs @@ -1385,8 +1385,9 @@ it once the pointer itself becomes unreachable. The garbage collector cannot see the copy that C holds. - Creating a callback takes microseconds. For a callback that C calls on each - of many calls, and that needs no per-call state, create it once and reuse it. + Creating a callback is not free in terms of performance, it takes about 2 us + on Node.js. In performance sensitive code, when possible, re-use a callback + rather than creating it for every invocation. CAUTION: Unregister the callback before its arena releases the pointer." [^Arena arena f argtypes rettype]