r/ProgrammerHumor • • Feb 05 '18

StackOverflow in a nutshell.

Post image
16.2k Upvotes

1.2k comments sorted by

View all comments

Show parent comments

4

u/ar-pharazon Feb 06 '18

it avoids allocating a new string (though it is destructive, meaning that if you needed your original, unreversed string, you're going to have to reverse it again).

your method has the benefit of not destroying the original, but the particular way you wrote it is prone to triggering extra allocations. if you're using java, consider the following:

String forwards = "forwards";
String rev = "";
for (int i = forwards.length() - 1; i >= 0; i--) rev = rev + forwards[i];

in every iteration of the loop, we're actually discarding the old value of rev and replacing it with a copy that has the new character appended. this means we're generating a lot of unnecessary garbage.

if, on the other hand, you're in c++ using something like string::append, you're probably going to end up doing a vector resize (or similar operation) at some point.

but the bottom line is that extra allocation is unnecessary because you know beforehand exactly how much memory you need: forwards.length() characters. the java code to do this with only one allocation is roughly:

String forwards = "forwards";
char[] rev = new char[forwards.length()];
for (int i = 0; i < forwards.length(); i++) rev[forwards.length() - i - 1] = forwards[i];
String result = new String(rev);

c++ would be similar, though you could use the fill constructor rather than having the intermediate char array.

1

u/PTRWP Feb 06 '18

Thanks for the explanation