sizzle icon indicating copy to clipboard operation
sizzle copied to clipboard

Avoid reading outside of collection bounds

Open mathiasbynens opened this issue 8 years ago • 5 comments

Consider the following collection:

const array = ['a', 'b', 'c'];

Retrieving array[0] can be done relatively quickly. However, when the property doesn’t exist on the receiver, JavaScript engines must continue to look up the prototype chain until either the property is found or the chain ends. This is inherently slower than not doing any prototype chain lookups. Retrieving an out-of-bounds index, e.g. array[3], triggers this scenario, resulting in decreased performance.

This patch changes the way some loops are written to avoid running into the slow case unnecessarily.


Similar patch for jQuery: https://github.com/jquery/jquery/pull/3769

mathiasbynens avatar Aug 29 '17 07:08 mathiasbynens

CLA assistant check
All committers have signed the CLA.

jsf-clabot avatar Aug 29 '17 07:08 jsf-clabot

Hey.

This looks nice to me. How this reflects on the byte size though? Maybe you could provide a small jsperf as well?

markelog avatar Aug 29 '17 08:08 markelog

This is pretty big... can you put together a jsPerf or other benchmark (example, and yes I'm aware of the irony) showing the value?

   raw     gz Sizes
 65502  19586 dist/sizzle.js
 19851   7421 dist/sizzle.min.js

   raw     gz Compared to master @ 840b647cd1ddd9d9aec3cde73af3f697fbf068d7
  +194    +51 dist/sizzle.js
   +82    +54 dist/sizzle.min.js

gibson042 avatar Sep 15 '17 20:09 gibson042

If the Chrome perf quirk was the main driver for this, that has been fixed.

dmethvin avatar Nov 04 '17 15:11 dmethvin

CLA Not Signed