NewsCrawler.org

Array.prototype.lastIndexOf in V8 made up to about 26000x faster

Chromium(V8)のArray.prototype.lastIndexOfを最大約26000倍高速化した
Array.prototype.lastIndexOf in V8 made up to about 26000x faster
Array.prototype.lastIndexOf in V8 made up to about 26000x faster
Image: zenn.dev

A patch by riya amemiya, an engineer at Dinii, speeds up Array.prototype.lastIndexOf in V8, which searches an array from the end for the last element strictly equal (===) to the search value and returns -1 when there is none. The patch splits the fast path by the array's ElementsKind[1] and by the type of the search value. Previously one generic loop served every element type: each element of a double array was packed into a HeapNumber[2] before StrictEqual, so scanning 1 million elements could trigger up to 1 million allocations, and the commit message notes packed-double scans carried an O(n) allocation and indirect comparison cost.

For double arrays, the new code compares raw float64 values directly in a tight loop. Because NaN === NaN is false, a search for NaN returns -1 without looping, and non-number search values such as strings cannot be stored in a double array at all, so those cases return -1 immediately; undefined, which can appear in a double array as a sentinel, gets a dedicated loop, while a hole[3] is skipped as before. For Smi[4] and object arrays, a TaggedEqual bit comparison runs first, with a float64 or StrictEqual comparison only when representations differ, as between 1 and 1.0. Since lastIndexOf never modifies the array, the fast path was widened from FastJSArray to FastJSArrayForRead, still clamping to the elements length because evaluating fromIndex can run user code that changes the array.

Benchmarks in d8 on an arm64.release build, with N = 100000, 5 warmup runs and the best of 8 rounds, show a search for 'x' in a packed double array dropping from 0.1544 ms/op to 0.000006 ms/op, up to about 26000x faster, and a NaN search about 21000x faster. Full numeric scans improved about 2.4-3.1x, while packed object arrays stayed at about 1.0x because StrictEqual remains on that path. The author notes the results vary with the machine and its warm-up state, since they were taken on a personal PC.

Read the original zenn.dev

Sources

  • Zenn JA

    Chromium(V8)のArray.prototype.lastIndexOfを最大約26000倍高速化した

    8 likes1 bookmark0 comments

Published: First seen: Читать по-русски

Open as a page