在块作用域功能方面,ES6与ES5相比有哪些优势?我的意思是,在这两种情况下,块看起来非常相似,那么它有什么不同,性能方面,哪种方法更好呢?
ES6块
{
function foo() {
return 1;
}
foo() === 1;
{
function foo() {
return 2;
}
foo() === 2;
}
foo() === 1;
}ES5块
(function () {
var foo = function () {
return 1;
}
foo() === 1;
(function () {
var foo = function () {
return 2;
}
foo() === 2;
})();
foo() === 1;
})();发布于 2016-12-07 23:15:09
下面是一个测试,用来展示哪个最快:
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>
我电脑上的结果:
https://stackoverflow.com/questions/41016098
复制相似问题