Why is lodash.each faster than native forEach?

前端 未结 4 1993
别跟我提以往
别跟我提以往 2020-12-04 14:16

I was trying to find the fastest way of running a for loop with its own scope. The three methods I compared were:

var a = \"t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t,t         


        
4条回答
  •  死守一世寂寞
    2020-12-04 14:47

    http://kitcambridge.be/blog/say-hello-to-lo-dash/

    The lo-dash developers explain (here and on a video) that the relative speed of the native forEach varies among browsers. Just because forEach is native does not mean that it is faster than a simple loop built with for or while. For one thing, the forEach has to deal with more special cases. Secondly, forEach uses callbacks, with the (potential) overhead of function invocation etc.

    chrome in particular is known (at least to the lo-dash developers) to have a relatively slow forEach. So for that browser, lo-dash uses it's own simple while loop to gain speed. Hence the speed advantage that you see (but others don't).

    By smartly opting into native methods — only using a native implementation if it’s known to be fast in a given environment — Lo-Dash avoids the performance cost and consistency issues associated with natives.

提交回复
热议问题