Complete API documentation for WebGPU Sorting Library
- Introduction
- GPUContext
- BitonicSorter
- RadixSorter
- BufferManager
- Validator
- Benchmark
- Type Definitions
- Error Handling
- Browser Compatibility
The WebGPU Sorting library provides high-performance GPU-accelerated sorting algorithms through a clean TypeScript API. All sorting operations are performed asynchronously and return detailed performance metrics.
import { GPUContext, BitonicSorter, Validator } from 'webgpu-sorting';
// 1. Initialize
const context = new GPUContext();
await context.initialize();
// 2. Create sorter
const sorter = new BitonicSorter(context);
// 3. Sort data
const data = new Uint32Array([5, 2, 8, 1, 9]);
const result = await sorter.sort(data);
// 4. Validate
const validation = Validator.validate(data, result.sortedData);
console.log(`Valid: ${validation.isValid}`);
// 5. Cleanup
sorter.destroy();
context.destroy();Manages WebGPU environment initialization and lifecycle.
constructor();Creates a new GPUContext instance.
Example:
const context = new GPUContext();Since: 1.0.0
Checks if the current environment supports WebGPU.
static isSupported(): booleanReturns:
boolean-trueif WebGPU is supported,falseotherwise
Example:
if (GPUContext.isSupported()) {
console.log('WebGPU is available');
} else {
console.log('WebGPU not supported - falling back to CPU');
}Since: 1.0.0
Initializes the WebGPU environment, requesting adapter and device.
async initialize(config?: GPUContextConfig): Promise<void>Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
config |
GPUContextConfig |
{} |
Optional configuration object |
config.powerPreference |
'low-power' | 'high-performance' |
'high-performance' |
Power preference hint |
Throws:
WebGPUNotSupportedError- WebGPU is not supported in this browserGPUAdapterError- Failed to obtain GPU adapterGPUDeviceError- Failed to obtain GPU device
Example:
const context = new GPUContext();
// High-performance mode (default)
await context.initialize();
// Or explicitly specify
await context.initialize({
powerPreference: 'high-performance',
});Since: 1.0.0
Gets the GPU device instance.
getDevice(): GPUDeviceReturns:
GPUDevice- The WebGPU device object
Throws:
Error- If device has not been initialized
Example:
const device = context.getDevice();
// Use device for custom operationsSince: 1.0.0
Releases all GPU resources associated with this context.
destroy(): voidExample:
context.destroy();
console.log('GPU resources released');Bitonic sort implementation optimized for GPU execution.
| Property | Value |
|---|---|
| Time Complexity | O(n log²n) |
| Space Complexity | O(1) - in-place |
| Comparison-based | Yes |
| Stable | No |
constructor(context: GPUContext)Parameters:
| Parameter | Type | Description |
|---|---|---|
context |
GPUContext |
An initialized GPUContext instance |
Example:
const sorter = new BitonicSorter(context);Since: 1.0.0
Sorts a Uint32Array using the bitonic sort algorithm.
async sort(data: Uint32Array): Promise<SortResult>Parameters:
| Parameter | Type | Description |
|---|---|---|
data |
Uint32Array |
Array of 32-bit unsigned integers to sort |
Returns:
Promise<SortResult> with the following properties:
| Property | Type | Description |
|---|---|---|
sortedData |
Uint32Array |
The sorted array |
gpuTimeMs |
number |
GPU computation time in milliseconds |
totalTimeMs |
number |
Total time including data transfer |
Notes:
- Arrays are automatically padded to the next power of 2
- Padding values are set to
0xFFFFFFFFand removed from output - For small arrays (<1000 elements), CPU sorting may be faster
Example:
const data = new Uint32Array([5, 2, 8, 1, 9]);
const result = await sorter.sort(data);
console.log('Sorted:', result.sortedData);
// Uint32Array [1, 2, 5, 8, 9]
console.log('GPU time:', result.gpuTimeMs.toFixed(2), 'ms');
console.log('Total time:', result.totalTimeMs.toFixed(2), 'ms');Since: 1.0.0
Releases all resources associated with this sorter.
destroy(): voidExample:
sorter.destroy();
// GPU buffers and pipelines are releasedRadix sort implementation optimized for GPU execution.
| Property | Value |
|---|---|
| Time Complexity | O(n × k), where k = number of digits |
| Space Complexity | O(n) - requires auxiliary array |
| Comparison-based | No |
| Stable | Yes |
constructor(context: GPUContext)Parameters:
| Parameter | Type | Description |
|---|---|---|
context |
GPUContext |
An initialized GPUContext instance |
Example:
const sorter = new RadixSorter(context);Since: 1.0.0
Sorts a Uint32Array using the radix sort algorithm.
async sort(data: Uint32Array): Promise<SortResult>Parameters:
| Parameter | Type | Description |
|---|---|---|
data |
Uint32Array |
Array of 32-bit unsigned integers to sort |
Returns:
Promise<SortResult> - Same as BitonicSorter.sort()
Algorithm Details:
- Uses 4-bit radix (16 buckets per pass)
- Performs 8 passes for 32-bit integers
- Parallel histogram computation on GPU
- Prefix sum computed on CPU (simplified implementation)
- Parallel scatter operation on GPU
Example:
const data = new Uint32Array([1000000, 500, 100, 999999]);
const result = await sorter.sort(data);
console.log('Sorted:', result.sortedData);
// Uint32Array [100, 500, 999999, 1000000]Since: 1.0.0
Releases all resources associated with this sorter.
destroy(): voidManages GPU buffer creation, data transfer, and disposal.
constructor(device: GPUDevice)Parameters:
| Parameter | Type | Description |
|---|---|---|
device |
GPUDevice |
A WebGPU device object |
Example:
const bufferManager = new BufferManager(context.getDevice());Since: 1.0.0
Aligns a size to the specified boundary.
static alignSize(size: number, alignment: number): numberParameters:
| Parameter | Type | Description |
|---|---|---|
size |
number |
Original size in bytes |
alignment |
number |
Alignment boundary in bytes |
Returns:
number- Aligned size
Example:
const aligned = BufferManager.alignSize(100, 256);
// Returns 256
const aligned2 = BufferManager.alignSize(300, 256);
// Returns 512Since: 1.0.0
Creates a storage buffer and uploads data to it.
createStorageBuffer(data: Uint32Array): GPUBufferParameters:
| Parameter | Type | Description |
|---|---|---|
data |
Uint32Array |
Data to upload |
Returns:
GPUBuffer- GPU buffer withSTORAGE | COPY_SRC | COPY_DSTusage
Example:
const data = new Uint32Array([1, 2, 3, 4, 5]);
const buffer = bufferManager.createStorageBuffer(data);
// Buffer is ready for compute shader operationsSince: 1.0.0
Creates a staging buffer for reading data from GPU.
createStagingBuffer(size: number): GPUBufferParameters:
| Parameter | Type | Description |
|---|---|---|
size |
number |
Buffer size in bytes |
Returns:
GPUBuffer- GPU buffer withMAP_READ | COPY_DSTusage
Since: 1.0.0
Reads data from a GPU buffer to CPU memory.
async readBuffer(buffer: GPUBuffer, size: number): Promise<Uint32Array>Parameters:
| Parameter | Type | Description |
|---|---|---|
buffer |
GPUBuffer |
GPU buffer to read from |
size |
number |
Number of bytes to read |
Returns:
Promise<Uint32Array>- The read data
Example:
const result = await bufferManager.readBuffer(gpuBuffer, 1024);
console.log('GPU data:', result);Provides validation utilities for sorting results.
All methods are static and can be called without instantiation.
Since: 1.0.0
Checks if an array is sorted in ascending order.
static isSorted(data: Uint32Array): booleanParameters:
| Parameter | Type | Description |
|---|---|---|
data |
Uint32Array |
Array to check |
Returns:
boolean-trueif sorted,falseotherwise
Example:
Validator.isSorted(new Uint32Array([1, 2, 3, 4, 5]));
// Returns true
Validator.isSorted(new Uint32Array([5, 2, 3, 1, 4]));
// Returns falseSince: 1.0.0
Checks if two arrays contain the same elements (order-independent).
static hasSameElements(a: Uint32Array, b: Uint32Array): booleanParameters:
| Parameter | Type | Description |
|---|---|---|
a |
Uint32Array |
First array |
b |
Uint32Array |
Second array |
Returns:
boolean-trueif arrays contain same elements
Example:
const a = new Uint32Array([1, 2, 3]);
const b = new Uint32Array([3, 1, 2]);
Validator.hasSameElements(a, b);
// Returns trueSince: 1.0.0
Performs complete validation of sorting results.
static validate(
input: Uint32Array,
output: Uint32Array
): ValidationResultParameters:
| Parameter | Type | Description |
|---|---|---|
input |
Uint32Array |
Original input array |
output |
Uint32Array |
Sorted output array |
Returns:
ValidationResult with the following properties:
| Property | Type | Description |
|---|---|---|
isValid |
boolean |
Overall validation result |
errors |
string[] |
List of error messages |
Validation Checks:
- Output array is sorted
- Input and output have same length
- Input and output contain same elements
Example:
const input = new Uint32Array([5, 2, 8, 1]);
const output = new Uint32Array([1, 2, 5, 8]);
const result = Validator.validate(input, output);
if (result.isValid) {
console.log('✅ Sorting correct');
} else {
console.error('❌ Sorting errors:', result.errors);
}Performance benchmarking utility for sorting algorithms.
constructor(context: GPUContext)Parameters:
| Parameter | Type | Description |
|---|---|---|
context |
GPUContext |
An initialized GPUContext instance |
Example:
const benchmark = new Benchmark(context);Since: 1.0.0
Formats benchmark results as a formatted table string.
static formatResults(results: BenchmarkResult[]): stringParameters:
| Parameter | Type | Description |
|---|---|---|
results |
BenchmarkResult[] |
Array of benchmark results |
Returns:
string- Formatted table
Example:
const table = Benchmark.formatResults(results);
console.log(table);
// │ Algorithm │ Size │ GPU Time │ Total Time │ Speedup │
// ├───────────┼────────┼──────────┼────────────┼─────────┤
// │ Bitonic │ 100000 │ 2.1ms │ 3.5ms │ 4.3x │Since: 1.0.0
Runs a single benchmark test.
async runSingle(
algorithm: 'bitonic' | 'radix',
size: number,
iterations: number
): Promise<BenchmarkResult>Parameters:
| Parameter | Type | Description |
|---|---|---|
algorithm |
'bitonic' | 'radix' |
Sorting algorithm to benchmark |
size |
number |
Array size |
iterations |
number |
Number of iterations to average |
Returns:
Promise<BenchmarkResult> with the following properties:
| Property | Type | Description |
|---|---|---|
algorithm |
'bitonic' | 'radix' | 'js-native' |
Algorithm name |
arraySize |
number |
Array size |
iterations |
number |
Number of iterations |
gpuTimeMs |
number | undefined |
Average GPU time (GPU algorithms only) |
totalTimeMs |
number |
Average total time |
speedupVsNative |
number | undefined |
Speedup vs native JS sort |
Example:
const result = await benchmark.runSingle('bitonic', 100000, 5);
console.log(`Speedup: ${result.speedupVsNative?.toFixed(2)}x`);
// Speedup: 7.50xSince: 1.0.0
Runs a complete benchmark suite.
async runAll(sizes: number[]): Promise<BenchmarkResult[]>Parameters:
| Parameter | Type | Description |
|---|---|---|
sizes |
number[] |
Array sizes to test |
Returns:
Promise<BenchmarkResult[]>- Results for all algorithm/size combinations
Example:
const results = await benchmark.runAll([1024, 10240, 102400]);
console.log(Benchmark.formatResults(results));Since: 1.0.0
Releases benchmark resources.
destroy(): voidConfiguration for GPU context initialization.
interface GPUContextConfig {
/**
* Power preference hint for GPU selection
* @default 'high-performance'
*/
powerPreference?: 'low-power' | 'high-performance';
}Result of a sorting operation.
interface SortResult {
/** Sorted array */
sortedData: Uint32Array;
/** GPU computation time in milliseconds */
gpuTimeMs: number;
/** Total time including data transfer in milliseconds */
totalTimeMs: number;
}Result of validation checks.
interface ValidationResult {
/** Whether validation passed */
isValid: boolean;
/** Error messages if validation failed */
errors: string[];
}Result of a benchmark test.
interface BenchmarkResult {
/** Algorithm used */
algorithm: 'bitonic' | 'radix' | 'js-native';
/** Array size tested */
arraySize: number;
/** Average GPU time in milliseconds */
gpuTimeMs?: number;
/** Average total time in milliseconds */
totalTimeMs: number;
/** Speedup compared to native JS sort */
speedupVsNative?: number;
/** Number of iterations */
iterations: number;
}The library provides detailed error types for different failure scenarios.
Error
├── WebGPUNotSupportedError
├── GPUAdapterError
├── GPUDeviceError
├── BufferAllocationError
├── BufferMapError
├── ShaderCompilationError
└── GPUTimeoutError
Thrown when the browser does not support WebGPU.
import { WebGPUNotSupportedError } from 'webgpu-sorting';
try {
await context.initialize();
} catch (error) {
if (error instanceof WebGPUNotSupportedError) {
console.error('Please use a WebGPU-enabled browser');
}
}Thrown when unable to obtain a GPU adapter.
Common causes:
- No compatible GPU available
- Drivers not installed or outdated
- GPU disabled in browser settings
Thrown when unable to obtain a GPU device.
Thrown when buffer allocation fails (typically out of memory).
Thrown when WGSL shader compilation fails.
| API | Chrome | Edge | Firefox | Safari |
|---|---|---|---|---|
| GPUContext | 113+ | 113+ | Nightly | 18+ |
| BitonicSorter | 113+ | 113+ | Nightly | 18+ |
| RadixSorter | 113+ | 113+ | Nightly | 18+ |
| Benchmark | 113+ | 113+ | Nightly | 18+ |
Notes:
- Firefox Nightly requires
dom.webgpu.enabledflag - Safari 18+ requires macOS 14+
- Performance varies significantly across browsers
// ✅ Good: Reuse context and sorter
const context = new GPUContext();
await context.initialize();
const sorter = new BitonicSorter(context);
for (const data of datasets) {
await sorter.sort(data);
}
sorter.destroy();
context.destroy();
// ❌ Bad: Create new instances for each sort
for (const data of datasets) {
const context = new GPUContext();
await context.initialize();
const sorter = new BitonicSorter(context);
await sorter.sort(data);
sorter.destroy();
context.destroy();
}| Array Size | Recommendation |
|---|---|
| < 1,000 | Use native JS Array.sort() |
| 1,000 - 10,000 | Bitonic or Radix, minimal benefit |
| 10,000 - 100,000 | Both algorithms show good speedup |
| > 100,000 | Significant GPU advantage |
await context.initialize({
powerPreference: 'high-performance',
});Last Updated: 2026-04-17
Version: 1.0.1