Skip to content

Instantly share code, notes, and snippets.

@qgustavor
Created November 28, 2021 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qgustavor/abf66fc4d8faf62c7e2f1a9e64cc077e to your computer and use it in GitHub Desktop.
Save qgustavor/abf66fc4d8faf62c7e2f1a9e64cc077e to your computer and use it in GitHub Desktop.
// Run in console in a page with sha256 loaded as a global
(async function () {
let durations = []
for (let i = 0; i < 100; i++) {
const times = 5000
const value = ''
const start = Date.now()
let hashHex = value
for (let i = 0; i < times; i++) {
const hashBuffer = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(hashHex).buffer)
const hashArray = Array.from(new Uint8Array(hashBuffer))
hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
}
durations.push(Date.now() - start)
}
console.log('CURRENT CODE:', durations.reduce((a, b) => a + b) / durations.length)
durations = []
for (let i = 0; i < 100; i++) {
const times = 5000
const value = ''
const start = Date.now()
let hashHex = value
for (let i = 0; i < times; i++) {
hashHex = sha256(value)
}
durations.push(Date.now() - start)
}
console.log('JSSHA', durations.reduce((a, b) => a + b) / durations.length)
durations = []
for (let i = 0; i < 100; i++) {
const start = Date.now()
const key = await window.crypto.subtle.importKey('raw', new Uint8Array(16), { name: 'PBKDF2' }, false, ['deriveBits'])
await window.crypto.subtle.deriveBits({
name: 'PBKDF2',
salt: new Uint8Array(16),
iterations: 5000,
hash: { name: 'SHA-256' }
}, key, 256)
durations.push(Date.now() - start)
}
console.log('PBKDF2', durations.reduce((a, b) => a + b) / durations.length)
}())

Chromium

96.0.4664.45 (Official Build, ungoogled-chromium) (64-bit)

CURRENT CODE: 468.07 ms
JSSHA 35.77 ms (12 times faster)
PBKDF2 14.22 ms (32 times faster)

Firefox

94.0b6 (64-bit)

CURRENT CODE: 923.35 ms
JSSHA 22.34 ms (40 times faster)
PBKDF2 2.09 ms (440 times faster)

Disclaimer: there were other processes opened which could affect the results and the benchmark code is not optimal (it doest not use performance.now(), a benchmark library would be better suited for this task, etc).

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