Skip to content

Commit 8b740e0

Browse files
authored
fix: use allocUnsafe where possible (#34)
Before: ``` Uint8Arrays.concat with length x 970,746 ops/sec ±1.19% (91 runs sampled) ``` After: ``` Uint8Arrays.concat with length x 1,688,327 ops/sec ±0.90% (87 runs sampled) ```
1 parent 0a18849 commit 8b740e0

File tree

3 files changed

+8
-3
lines changed

3 files changed

+8
-3
lines changed

src/concat.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { allocUnsafe } from './alloc.js'
2+
13
/**
24
* Returns a new Uint8Array created by concatenating the passed ArrayLikes
35
*
@@ -9,7 +11,7 @@ export function concat (arrays, length) {
911
length = arrays.reduce((acc, curr) => acc + curr.length, 0)
1012
}
1113

12-
const output = new Uint8Array(length)
14+
const output = allocUnsafe(length)
1315
let offset = 0
1416

1517
for (const arr of arrays) {

src/util/bases.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { bases } from 'multiformats/basics'
2+
import { allocUnsafe } from '../alloc.js'
23

34
/**
45
* @typedef {import('multiformats/bases/interface').MultibaseCodec<any>} MultibaseCodec
@@ -43,7 +44,7 @@ const ascii = createCodec('ascii', 'a', (buf) => {
4344
return string
4445
}, (str) => {
4546
str = str.substring(1)
46-
const buf = new Uint8Array(str.length)
47+
const buf = allocUnsafe(str.length)
4748

4849
for (let i = 0; i < str.length; i++) {
4950
buf[i] = str.charCodeAt(i)

src/xor.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { allocUnsafe } from './alloc.js'
2+
13
/**
24
* Returns the xor distance between two arrays
35
*
@@ -9,7 +11,7 @@ export function xor (a, b) {
911
throw new Error('Inputs should have the same length')
1012
}
1113

12-
const result = new Uint8Array(a.length)
14+
const result = allocUnsafe(a.length)
1315

1416
for (let i = 0; i < a.length; i++) {
1517
result[i] = a[i] ^ b[i]

0 commit comments

Comments
 (0)