块范围功能:ECMAScript 6与ECMAScript 5

时间:2016-12-07 11:18:46

标签: javascript

关于块范围功能,ES6相对于ES5有什么优势?我的意思是在这两种情况下块看起来非常相似所以它有什么不同,性能明智哪种方法更好用?

ES6 Block

@foreach ($name as $card)
    <li class="list-group-item"><span id="copy{{ $card->id }}">{{ $card->vhackIP }}</span> | {{ $card->name }} | {{ $card->description }}
         <button class="btn btn-success btn-xs" data-clipboard-target="#copy{{ $card->id }}">Copy IP</button>
    </li>
@endforeach

ES5 Block

{
    function foo() {
        return 1;
    }

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

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

1 个答案:

答案 0 :(得分:1)

这是一个测试,以显示哪个是最快的:

document.getElementById('btn').addEventListener('click', ({ target }) => {
  target.disabled = true;
  target.innerHTML = "Running&hellip;";
  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%
  •   
  • ES5:~2,425,847 ops / sec(~412 ns / op)
  •