Skip to content

Instantly share code, notes, and snippets.

@bwasti
Created August 20, 2022 18:50
Show Gist options
  • Save bwasti/58996256308e646947d7b77f21e4b304 to your computer and use it in GitHub Desktop.
Save bwasti/58996256308e646947d7b77f21e4b304 to your computer and use it in GitHub Desktop.
// g++ ptr_test.cc --shared -o ptr_test.so
#include <cstdint>
static uint32_t g_p = 0;
extern "C" {
void* gen_ptr() {
return (void*)&g_p;
}
void digest_ptr(void* p) {
(*(uint32_t*)p) ++;
}
}
import * as ffi from "bun:ffi"
const link = ffi.dlopen("ptr_test.so", {
gen_ptr: {
returns: ffi.FFIType.ptr
},
digest_ptr: {
args: [ffi.FFIType.ptr]
}
})
const lib = link.symbols
function withToArrayBuffer() {
const p = lib.gen_ptr();
const a = ffi.toArrayBuffer(p, 0, 1);
lib.digest_ptr(ffi.ptr(a));
}
function withoutToArrayBuffer() {
const p = lib.gen_ptr();
lib.digest_ptr(p);
}
for (let i = 0; i < 100000; ++i) {
withToArrayBuffer();
withoutToArrayBuffer();
}
const iters = 10000000;
{
const t0 = performance.now();
for (let i = 0; i < iters; ++i) {
withToArrayBuffer();
}
const t1 = performance.now();
console.log("toArrayBuffer", (t1-t0) * 1e6 / iters, "ns/iter");
}
{
const t0 = performance.now();
for (let i = 0; i < iters; ++i) {
withoutToArrayBuffer();
}
const t1 = performance.now();
console.log("Without toArrayBuffer", (t1-t0) * 1e6 / iters, "ns/iter");
}
@bwasti
Copy link
Author

bwasti commented Aug 20, 2022

On a canary build, this is the output:

toArrayBuffer 135.7197583 ns/iter
Without toArrayBuffer 34.2141875 ns/iter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment