node/benchmark/ffi/sum-buffer.js
Bryan English 528f8b2bae
ffi: add shared-buffer fast path for numeric and pointer signatures
Adds an ArrayBuffer-based invocation path for FFI functions whose
signatures are composed entirely of numeric types (i8..i64, u8..u64,
f32, f64, bool, char) and/or pointer types. The JS wrapper packs
arguments directly into a per-function AB via primordial DataView
setters and the C++ invoker (`InvokeFunctionSB`) reads them without
going through V8's `FunctionCallbackInfo`. Results are returned the same
way.

Pointer arguments use runtime dispatch: BigInt, null, and undefined take
the fast path, while Buffer, ArrayBuffer, ArrayBufferView, and String
fall back transparently to the classic `InvokeFunction` path via a
stashed `_invokeSlow` function. Signatures containing
non-numeric/non-pointer types also bypass the fast path.

The fast path is disabled on big-endian platforms.

Callers do not opt in, and the fast path is transparent in every way
users should rely on. One observable change: function wrappers returned
by `library.getFunction`, `library.getFunctions`, and `library.functions`
now have `.length` equal to the declared parameter count rather than
`0`. Code that relied on the previous value will need to be updated.

Adds microbenchmarks covering the common FFI call shapes so future
changes to the invoker can be evaluated:

- add-i32.js: 2-arg integer
- add-f64.js: 2-arg float
- many-args.js: 6-arg integer
- pointer-bigint.js: 1-arg pointer (BigInt)
- sum-buffer.js: pointer + length (Buffer)

A `common.js` helper resolves the fixture-library path from
`test/ffi/fixture_library` without pulling in the test harness, and
throws a clear message if the fixture hasn't been built yet.

Also adds `sum_6_i32` to the fixture library for the many-args case.

Signed-off-by: Bryan English <bryan@bryanenglish.com>
PR-URL: https://github.com/nodejs/node/pull/62918
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
Reviewed-By: Paolo Insogna <paolo@cowtech.it>
2026-05-05 16:19:54 +02:00

33 lines
707 B
JavaScript

'use strict';
const common = require('../common.js');
const ffi = require('node:ffi');
const { libraryPath, ensureFixtureLibrary } = require('./common.js');
const bench = common.createBenchmark(main, {
size: [64, 1024, 16384],
n: [1e6],
}, {
flags: ['--experimental-ffi'],
});
ensureFixtureLibrary();
const { lib, functions } = ffi.dlopen(libraryPath, {
sum_buffer: { result: 'u64', parameters: ['pointer', 'u64'] },
});
function main({ n, size }) {
const buf = Buffer.alloc(size, 0x42);
const ptr = ffi.getRawPointer(buf);
const len = BigInt(size);
const sum = functions.sum_buffer;
bench.start();
for (let i = 0; i < n; ++i)
sum(ptr, len);
bench.end(n);
lib.close();
}