Yeah, I know what you mean. I literally only learned this a few days ago!
As you do more benchmark testing you begin to see what sorts of thing ‘cost’ more. In your example, even though the code is shorter, you are asking the function to make an array, reverse the array, and then join it back up and turn it back into a string.
That sounds easy enough, but the hidden costs are probably in those string and array methods you are calling (
Each of those are their own functions (methods). Imagine how you would
spilt a string into an array of individual letters. You’d probably make the array, then do a for loop through the string pushing each letter to the array. Then to
reverse that array, you’d probably make another array and use a for loop to push each of those to the new array in reverse order. Then to
join it up you’d likely need another for loop to take each item in the new array and concatenate a string.
Once you think through how you’d implement the string and array methods yourself, it’s easier to spot potentially hidden loops and temporary object creation that add processing overhead.
Note: I haven’t actually read the code for the
join methods, so I may be way off in my guess as to how they are implemented!