Repository navigation
perf(arrays): O(1) shift() on fast arrays - #7
Merged
Merged
Conversation
…elements Array.prototype.shift() moved all the elements of a fast array, so a queue built with push() and shift() was O(n^2). shift() now advances the element pointer and counts the free slots before it (u.array.offset, which fits in the padding of JSObject). expand_fast_array() moves the elements back to the start of the allocation when the free slots are at least half as many as the elements (at most 2 copied elements per shift() call), otherwise it reallocates the whole block and keeps them.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
shift()moved every remaining element, so push/shift queues were O(n²). It now advances the element pointer and counts the free slots in front (u.array.offset, which fits in existingJSObjectpadding).expand_fast_array()compacts once the free slots reach half the element count, so it copies at most 2 elements pershift().shift()Memory:
JSObjectdoesn't get any bigger, since the new field fits in existing padding. The trade-off is that a queue that stays the same size can now hold up to about 2.25× its live elements, against about 1.5× before. In my queue test that came to roughly 5% more memory.Tested with an array-operation fuzz (same output as master), the snapshot suite and test262.
Reviewer note: everything that frees or replaces the elements pointer goes through
fast_array_base(), so the offset can't leak anywhere. Only plain arrays ever get a non-zero offset; arguments objects and typed arrays always keep it at 0.Open in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.