Why is using a generator function slower than filling and iterating an array in this example?

后端 未结 4 1487
温柔的废话
温柔的废话 2021-02-12 21:26

A Tale of Two Functions

I have one function that fills an array up to a specified value:

function getNumberArray(maxValue) {
    const a         


        
相关标签:
4条回答
  • 2021-02-12 21:27

    In fact, running this benchmark now, generators at ~2x faster.

    I've modified the code slightly (moved let i) and here is the full gist: https://gist.github.com/antonkatz/6b0911c85ddadae39c434bf8ac32b340

    On my machine, these are the results:

    Running Array... Total time: 4,022ms Rss: 2,728,939,520 Heap Total: 2,726,199,296 Heap Used: 2,704,236,368

    Running Generator... Total time: 2,541ms Rss: 851,968 Heap Total: 0 Heap Used: -5,073,968

    I was very curious myself and could not find a proper answer. Thanks @David for providing the test code.

    0 讨论(0)
  • 2021-02-12 21:31

    The terribly unsatisfying answer is probably this: Your ES5 function relies on features that (with the exceptions of let and const) have been in V8 since it was released in 2008 (and presumably for some time before, as I understand that what became V8 originated as part of Google's web crawler). Generators, on the other hand, have only been in V8 since 2013. So not only has the ES5 code had seven years to be optimized while the ES6 code has had only two, almost nobody (compared to the many millions of sites using code just like your ES5 code) is using generators in V8 yet, which means there has been very little opportunity to discover, or incentive to implement, optimizations for it.

    If you really want a technical answer as to why generators are comparatively slow in Node.js, you'll probably have to dive into the V8 source yourself, or ask the people who wrote it.

    0 讨论(0)
  • 2021-02-12 21:34

    Try replacing the 'let' in the generator function with a function scoped 'var'. It seems that the 'let' inside the loop incurs a lot of overhead. Only use let if you absolutely have to.

    0 讨论(0)
  • 2021-02-12 21:36

    FYI this question is ancient in internet terms and generators have caught up (at least when tested in Chrome) https://jsperf.com/generator-vs-loops1

    0 讨论(0)
提交回复
热议问题