gpt4 book ai didi

javascript - block 作用域函数: ECMAScript 6 vs ECMAScript 5

转载 作者:太空宇宙 更新时间:2023-11-04 16:16:48 25 4
gpt4 key购买 nike

在 block 作用域函数方面,ES6 相对于 ES5 有哪些优势?我的意思是,在这两种情况下,该 block 看起来非常相似,那么它有什么区别,性能方面哪种方法更好?

ES6 block

{
function foo() {
return 1;
}

foo() === 1;
{
function foo() {
return 2;
}

foo() === 2;
}
foo() === 1;
}

ES5 block

(function () {
var foo = function () {
return 1;
}
foo() === 1;
(function () {
var foo = function () {
return 2;
}
foo() === 2;
})();
foo() === 1;
})();

最佳答案

这里有一个测试来显示哪个最快:

document.getElementById('btn').addEventListener('click', ({ target }) => {
target.disabled = true;
target.innerHTML = "Running…";
const suite = new Benchmark.Suite();
document.getElementById('ES6').style.fontWeight = '';
document.getElementById('ES5').style.fontWeight = '';
suite.add('ES6', () => {
{
function foo() {
return 1;
}
foo() === 1;
{
function foo() {
return 2;
}
foo() === 2;
}
foo() === 1;
}
}).add('ES5', () => {
(function () {
var foo = function () {
return 1;
}
foo() === 1;
(function () {
var foo = function () {
return 2;
}
foo() === 2;
})();
foo() === 1;
})();
})
.on('cycle', ({target: bench}) => document.getElementById(bench.name).textContent = `${bench.name}: ~${Benchmark.formatNumber(bench.hz|0)} ops/sec (~${Benchmark.formatNumber(Math.round(1e9/bench.hz))} ns/op)`)
.on('complete', function() {
const el = document.getElementById(this.filter('fastest').map('name')[0]),
hz = this.filter('fastest').map('hz')[0],
others = this.filter('slowest').map('hz'),
avg = others.reduce((a, b) => a + b, 0) / others.length;
el.style.fontWeight = 'bold';
el.textContent += ` \u{1f451} ${Math.round((1 - avg / hz) * 100, 2)}% faster`;
target.disabled = false;
target.innerHTML = "Run";
})
.run({ 'async': true });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/2.1.2/benchmark.min.js"></script>
<ul>
<li id="ES6"></li>
<li id="ES5"></li>
</ul>
<button id="btn">Run</button>

我的计算机上的结果:

  • ES6: ~3,896,305 ops/sec (~257 ns/op) 👑 40% faster
  • ES5: ~2,425,847 ops/sec (~412 ns/op)

关于javascript - block 作用域函数: ECMAScript 6 vs ECMAScript 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41016098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com