Complete API documentation for WebGPU Sorting.
Manages WebGPU device lifecycle.
import { GPUContext } from 'webgpu-sorting';Check if WebGPU is available in the current environment.
if (GPUContext.isSupported()) {
// WebGPU is available
}Create a new GPU context instance.
const gpu = new GPUContext();Initialize the WebGPU device.
interface GPUContextConfig {
powerPreference?: 'low-power' | 'high-performance';
}
await gpu.initialize({
powerPreference: 'high-performance',
});Get the underlying WebGPU device.
const device = gpu.getDevice();Release GPU resources.
gpu.destroy();GPU-accelerated Bitonic Sort implementation.
import { BitonicSorter } from 'webgpu-sorting';Create a new Bitonic sorter.
const sorter = new BitonicSorter(gpu);Sort an array of unsigned 32-bit integers.
interface SortOptions {
validate?: boolean; // Verify output is sorted (default: false)
}
interface SortResult {
sortedData: Uint32Array; // The sorted array
gpuTimeMs: number; // GPU execution time
totalTimeMs: number; // Total time including transfers
}
const result = await sorter.sort(data, { validate: true });Release GPU resources used by the sorter.
sorter.destroy();Preallocate GPU buffers for sorting arrays up to maxSize. Buffers are reused across multiple sort() calls for better performance in batch sorting scenarios.
sorter.preallocate(1_000_000); // Preallocate for up to 1M elements
// Multiple sorts reuse the same buffers
for (const arr of arrays) {
const result = await sorter.sort(arr);
}Release preallocated buffers. Buffers will be allocated on-demand for subsequent sorts.
sorter.clearPreallocation();Returns the current preallocation size, or 0 if not preallocated.
console.log(sorter.preallocatedSize); // 1000000 or 0GPU-accelerated Radix Sort implementation.
import { RadixSorter } from 'webgpu-sorting';Create a new Radix sorter.
const sorter = new RadixSorter(gpu);Sort an array of unsigned 32-bit integers.
const result = await sorter.sort(data);::: tip Best For Radix Sort is optimized for Uint32Array datasets. For other data types, use BitonicSorter. :::
Release GPU resources used by the sorter.
sorter.destroy();Preallocate GPU buffers for sorting arrays up to maxSize. Buffers are reused across multiple sort() calls for better performance in batch sorting scenarios.
sorter.preallocate(1_000_000); // Preallocate for up to 1M elements
// Multiple sorts reuse the same buffers
for (const arr of arrays) {
const result = await sorter.sort(arr);
}Release preallocated buffers. Buffers will be allocated on-demand for subsequent sorts.
sorter.clearPreallocation();Returns the current preallocation size, or 0 if not preallocated.
console.log(sorter.preallocatedSize); // 1000000 or 0Thrown when WebGPU is not available in the browser.
import { WebGPUNotSupportedError } from 'webgpu-sorting';
try {
await gpu.initialize();
} catch (error) {
if (error instanceof WebGPUNotSupportedError) {
// Browser doesn't support WebGPU
}
}Thrown when GPU adapter acquisition fails.
import { GPUAdapterError } from 'webgpu-sorting';Thrown when GPU device acquisition fails.
import { GPUDeviceError } from 'webgpu-sorting';Thrown when GPU buffer allocation fails.
import { BufferAllocationError } from 'webgpu-sorting';Thrown when WGSL shader compilation fails.
import { ShaderCompilationError } from 'webgpu-sorting';interface SortOptions {
/**
* Verify the output is correctly sorted after sorting completes.
* Useful for debugging and testing.
* @default false
*/
validate?: boolean;
}interface SortResult {
/**
* The sorted array
*/
sortedData: Uint32Array;
/**
* GPU execution time in milliseconds
*/
gpuTimeMs: number;
/**
* Total time including data transfer in milliseconds
*/
totalTimeMs: number;
}interface GPUContextConfig {
/**
* GPU power preference
* @default 'high-performance'
*/
powerPreference?: 'low-power' | 'high-performance';
}Default workgroup size for compute shaders.
import { WORKGROUP_SIZE } from 'webgpu-sorting';
// Value: 256Maximum buffer size supported.
import { MAX_BUFFER_SIZE } from 'webgpu-sorting';
// Value: Device dependentconst gpu = new GPUContext();
await gpu.initialize();
const sorter = new BitonicSorter(gpu);
const data = new Uint32Array([5, 2, 8, 1, 9]);
const { sortedData } = await sorter.sort(data);
gpu.destroy();const gpu = new GPUContext();
await gpu.initialize();
const sorter = new BitonicSorter(gpu);
const arrays = [
new Uint32Array([3, 1, 4, 1, 5]),
new Uint32Array([9, 2, 6, 5, 3]),
new Uint32Array([8, 9, 7, 9, 3]),
];
for (const arr of arrays) {
const result = await sorter.sort(arr);
console.log(result.sortedData);
}
gpu.destroy();async function safeSort(data: Uint32Array): Promise<Uint32Array> {
if (!GPUContext.isSupported()) {
return data.slice().sort((a, b) => a - b);
}
try {
const gpu = new GPUContext();
await gpu.initialize();
const sorter = new BitonicSorter(gpu);
const result = await sorter.sort(data);
gpu.destroy();
return result.sortedData;
} catch (error) {
console.warn('GPU sort failed, using CPU fallback:', error);
return data.slice().sort((a, b) => a - b);
}
}async function compareSorters(size: number) {
const data = new Uint32Array(size);
for (let i = 0; i < size; i++) data[i] = Math.random() * 1_000_000;
const gpu = new GPUContext();
await gpu.initialize();
const bitonic = new BitonicSorter(gpu);
const radix = new RadixSorter(gpu);
const r1 = await bitonic.sort(data);
const r2 = await radix.sort(data);
console.log(`Bitonic: ${r1.gpuTimeMs}ms`);
console.log(`Radix: ${r2.gpuTimeMs}ms`);
gpu.destroy();
}