偶尔发现一个想不通的问题
'use strict'
const POSSIBLE = '0123456789ABCDEF'
function test01() {
let session_id = ''
for (let i = 0; i < 8; i++) {
session_id += POSSIBLE[(Math.floor(Math.random() * POSSIBLE.length))]
}
}
function test02() {
var session_id = ''
for (var i = 0; i < 8; i++) {
session_id += POSSIBLE[(Math.floor(Math.random() * POSSIBLE.length))]
}
}
;[test01, test02].forEach((func) => {
let count = 1000 * 1000
let now = Date.now()
for (let i = 0; i < count; i++) {
func()
}
let use_time = Date.now() - now
console.log('Count = %d, Use Time = %d ms, Cost = %d ms/t', count, use_time, (use_time / count))
})
结果: Count = 1000000, Use Time = 780 ms, Cost = 0.00078 ms/t Count = 1000000, Use Time = 250 ms, Cost = 0.00025 ms/t
10 回复
我试了一下
块级作用域所增加的环境对象对性能影响不是很大, 影响大的+=
作用于let
声明的变量.(其它操作符没具体测试, 试了++
, 影响不大)
试试下面的代码
'use strict'
const POSSIBLE = '0123456789ABCDEF'
function test01() {
let session_id = ''
for (let i = 0; i < 8; i++) {
// session_id += POSSIBLE[(Math.floor(Math.random() * POSSIBLE.length))]
session_id = session_id + POSSIBLE[(Math.floor(Math.random() * POSSIBLE.length))]
}
}
function test02() {
var session_id = ''
for (var i = 0; i < 8; i++) {
// session_id += POSSIBLE[(Math.floor(Math.random() * POSSIBLE.length))]
session_id = session_id + POSSIBLE[(Math.floor(Math.random() * POSSIBLE.length))]
}
}
;[test01, test02].forEach((func) => {
let count = 1000 * 1000
let now = Date.now()
for (let i = 0; i < count; i++) {
func()
}
let use_time = Date.now() - now
console.log('Count = %d, Use Time = %d ms, Cost = %d ms/t', count, use_time, (use_time / count))
})
// [email protected]
Count = 1000000, Use Time = 347 ms, Cost = 0.000347 ms/t
Count = 1000000, Use Time = 322 ms, Cost = 0.000322 ms/t