DEV Community

loading...

Discussion on: Reverse a String - Four JavaScript Solutions

Collapse
aminmansuri profile image
hidden_dude • Edited

Wouldn't solution #2 (and maybe some of the others) cause an O(n2 ) problem?

for (let character of str) {
    reverseString = character + reverseString;
}

If str has N elements, and you do character + reverseString each time you get n*(n+1)/2 characters copied (ie. O(n2 )).

Whereas option#1 presumably uses only O(n) functions so it should be much faster as data grows and less stress on the GC.

I think it would be best to compare these with benchmarks (with large examples). Because I've found that the one place where code can get super slow is with successive concatenation in a for loop (as in option#2).

Collapse
sarah_chima profile image
Sarah Chima Author

Thanks for the suggestion and the analysis. In subsequent posts, I try to compare the solutions based on their performance.