鍍金池/ 問答/HTML/ 為什么crypto.pbkdf2Sync比crypto.pbkdf2耗時(shí)嚴(yán)重?

為什么crypto.pbkdf2Sync比crypto.pbkdf2耗時(shí)嚴(yán)重?

在看 nodejs調(diào)試指南 中看到同步的時(shí)候在C++層面crypto::PBKDF2消耗時(shí)間比異步的高。

  1. 看不懂C++所以沒法從源碼看,想簡單了解一下為什么會導(dǎo)致這樣的結(jié)果。
  2. 其他方法是否類似,比如readfile/readfilesync。

同步pbkdf2

const crypto = require('crypto')

function hash (password) {
  const salt = crypto.randomBytes(128).toString('base64')
  const hash = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512')
  return hash
}

console.time('pbkdf2Sync')
for (let i = 0; i < 100; i++) {
  hash('random_password')
}
console.timeEnd('pbkdf2Sync')//pbkdf2Sync: 917.546ms

異步pbkdf2

const crypto = require('crypto')

function hash (password, cb) {
  const salt = crypto.randomBytes(128).toString('base64')
  crypto.pbkdf2(password, salt, 10000, 64, 'sha512', cb)
}

let count = 0
console.time('pbkdf2')
for (let i = 0; i < 100; i++) {
  hash('random_password', () => {
    count++
    if (count === 100) {
      console.timeEnd('pbkdf2')//pbkdf2: 303.675ms
    }
  })
}
回答
編輯回答
兔囡囡

首先你這個(gè)測試是不對的,同步版測的是100次同步hash調(diào)用,而異步版是其中的某一次hash調(diào)用。

console.time('pbkdf2Async');
function test(count) {
  if (count >= 100) {
    console.timeEnd('pbkdf2Async');
    return;
  }
  hash('random_password', (h) => test(count + 1))
}
test(0)

})()

差異并不大,次數(shù)加大,同步甚至?xí)犬惒娇臁?/del>

2018年8月10日 09:54