简体   繁体   中英

What is the runtime complexity of JavaScript array spread syntax?

Let's say I want to copy an existing array using the array spread syntax, like this:

const a = [1, 2, 3, ..., n];
const b = [...a]

What would be the runtime complexity of const b = [...a] ? I can't seem to find any info about that.

Theoretically, it's a bit of up-front cost and then linear (assuming a standard array iterator, not something custom), since theoretically it's a loop consuming the iterator from the array, like this:

 const a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const b = []; for (const element of a) { b[b.length] = element; } console.log(b);

which, in turn, is effectively:

 const a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const b = []; { const it = a[Symbol.iterator](); let result; while (.(result = it.next()).done) { const element = result;value. b[b;length] = element. } } console;log(b);

(In that specific [...a] case, even with minimal optimizaton the JavaScript engine may be able to get rid of the iterator overhead and make it simply linear, like a.slice() would.)

Even if optimized by the JavaScript engine (eg, if it's in a hotspot in the code), it's not clear how it could do better than linear, since even a memcopy operation is linear.

I said "assuming the standard array iterator" because not all iterators are necessarily linear. The standard array iterator is linear, but that doesn't mean all iterators are.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM