News for hackers. Stuff that matters.
Re:Left-Pad (2024) by barbegal on Wednesday June 11, 2025 @05:50AM (#44245850)
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.
Re:Left-Pad (2024) by lifthrasiir on Wednesday June 11, 2025 @06:08AM (#44245951)
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.
Re:Left-Pad (2024) by bondarchuk on Wednesday June 11, 2025 @06:37AM (#44246132)
"The compiler will take care of it", funny, heard that one before, I'd profile it just to be on the safe side...
Re:Left-Pad (2024) by lifthrasiir on Wednesday June 11, 2025 @06:39AM (#44246143)
I didn't mean that. JS doesn't have any lower-level interface for handling memory, so such optimization has to be in the implementation. It should be quite obvious that relying on such optimization can be problematic.