Skip to content

perf(arrays): O(1) shift() on fast arrays - #7

Merged
can1357 merged 1 commit into
stencil-hq:masterfrom
H4vC:perf/array-shift-offset
Nov 8, 2026
Merged

can1357 merged 1 commit into
stencil-hq:masterfrom
H4vC:perf/array-shift-offset

Conversation

@H4vC

@H4vC H4vC commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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 existing JSObject padding). expand_fast_array() compacts once the free slots reach half the element count, so it copies at most 2 elements per shift().

Case master PR
Drain 100k with shift() 2620 ms 8 ms (330×)
10k queue, 2M rotations 9450 ms 134 ms (70×)
BFS-style queue, 1M steps 160 s 86 ms
Drain/refill 1k ×2k 794 ms 146 ms (5×)
1M push/pop 120 ms 81 ms

Memory: JSObject doesn'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.


Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

…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.
@can1357
can1357 merged commit ca7ccd3 into stencil-hq:master Nov 8, 2026
can1357 added a commit that referenced this pull request Nov 8, 2026
Lands #7 (2cc2532) with the python/listobject.c fix it needs on master.

# Conflicts:
#	Changelog
#	tests/test_builtin.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants