Anything that is using symbol-by-symbol string concatenation would build a large number of strings instead of a single one that 'join' makes and would chew memory like crazy on large strings.
You might save a tiny portion of time on a single operation in a microbench, but gc kicking in sooner would destroy that benefit and will make matters worse.
The first variant here (split/reverse/join) is both the shortest, the most readable, and the less memory consuming one.
Note that unlike a very simple microbench, it actually retains those strings (i.e. puts the results into an array), which is a bit closer to what you might see in actual application.
The first method consumes 103 MiB.
The char-by-char concat methods consume over 1 GiB, and are slower.
Also, longer and less readable.
Bonus: try replacing 100 with 200 (the number of strigs in the for loop).
split/reverse/join consumes 170 MiB and 7 seconds.
The last two (reduce and «reverseString») die with OOM after 19 seconds.
That is also valid for shorter strings, e.g. try with 10000 (and 50000) of strings with length = 1000.
Anything that is using symbol-by-symbol string concatenation would build a large number of strings instead of a single one that 'join' makes and would chew memory like crazy on large strings.
You might save a tiny portion of time on a single operation in a microbench, but gc kicking in sooner would destroy that benefit and will make matters worse.
The first variant here (split/reverse/join) is both the shortest, the most readable, and the less memory consuming one.
Here is an test that reverses 100 different strings with length 200000 (±6):
Note that unlike a very simple microbench, it actually retains those strings (i.e. puts the results into an array), which is a bit closer to what you might see in actual application.
The first method consumes 103 MiB.
The char-by-char concat methods consume over 1 GiB, and are slower.
Also, longer and less readable.
Bonus: try replacing 100 with 200 (the number of strigs in the
for
loop).split/reverse/join consumes 170 MiB and 7 seconds.
The last two (reduce and «reverseString») die with OOM after 19 seconds.
That is also valid for shorter strings, e.g. try with 10000 (and 50000) of strings with length = 1000.
10000 iterations, 1000 length = 50 MiB / 1 second vs 520 MiB / 2 seconds.
50000 iterations, 1000 length = 129 MiB / 5 seconds vs OOM / 14 seconds.