Extending strings is not a linear-time operation. Behind the scenes, the JS runtime allocates new memory for it. In the naive case, you start by allocating 1 byte, then when you append to it, you need 2 bytes. So you allocate a new string of 2 bytes, and copy the data in. Each new byte is a new allocation, and a new copy of the entire string. That's how it's quadratic.
In practice, memory allocators tend to double the size of an allocation like this, which is still quadratic.
In practice, JS runtimes also tend to use data structures like Ropes for strings to handle this sort of issue. That brings it down to linear time in practice (I think?)
In each loop prepending a single character could take O(m) (moving all m characters one to the right) so combined O(nm) where n is the number of padding characters and m is the total number of characters in the string.
Only when the underlying JS implementation does this naively. In reality JS implementations do a lot of optimizations which often can reduce the time complexity.
pbiggar|8 months ago
In practice, memory allocators tend to double the size of an allocation like this, which is still quadratic.
In practice, JS runtimes also tend to use data structures like Ropes for strings to handle this sort of issue. That brings it down to linear time in practice (I think?)
barbegal|8 months ago
lifthrasiir|8 months ago
arcastroe|8 months ago
That linear-time operation is then additionally repeated `len` times
unknown|8 months ago
[deleted]