stevendesu / jsindex

1 stars 0 forks source link

Research object key iteration issues #16

Open stevendesu opened 5 years ago

stevendesu commented 5 years ago

Per #13, it was discovered that iterating over the keys in an object leads to intermittent performance issues. I suspect it is unexpectedly allocating memory and triggering garbage collection.

I need to do some research into what causes this so we can try to avoid it entirely. Maybe in the process I'll find a more efficient way to handle for...in that's even faster!

stevendesu commented 5 years ago

While sitting in the shower yesterday I actually came up with a hypothesis that I believe explains this behavior, and I wish I'd written it down at the time instead of relying on my terrible memory to last 24 hours.

I know the gist of it came down to JavaScript being dynamically typed, and several compiler optimizations being type-dependent. Because arrays in JavaScript are not fixed width, they must be stored on the heap and not the stack. Therefore all elements within the array are pointers in the heap, not pointers in the stack. For non-objects, which are passed by value and not by reference, it is therefore necessary to create a copy whenever you perform an array access operation to avoid accidentally overwriting the value referenced by the pointer.

In my example I used integers in the array, which means that every time I modified the value I was actually secretly allocating new memory (to simulate pass-by-value for pointers on the heap). Because this library only supports arrays of objects (which are pass by reference) this may not be an issue in most cases.