Reputation: 1111
I have a large array that I'll be reversing then joining with a string. I'm afraid that reversing will iterate through every element in the array in O(n) time, although theoretically just flipping a boolean that tracks if the array is reversed would do in O(1) time, then instead of using the join function just looping through and joining myself in opposite order.
So instead of:
arr.reverse().join(',')
I could just do:
let tmp = '';
for(let i=arr.length-1; i>=0; i--)
tmp += arr[i] + ',';
then remove the last comma.
Is Array.reverse() slow? Should I not worry about the computational efficiency for just a few thousand items?
Note: I have viewed this question, it is different: Array.Reverse algorithm?. Please do not flag as duplicate unless the question is the same.
Upvotes: 0
Views: 5481
Reputation: 145
Time complexity O(n): https://learnersbucket.com/examples/algorithms/how-to-reverse-an-array-in-javascript/
Should I not worry about the computational efficiency for just a few thousand items?
For a few thousand items, you will probably not notice the difference. In general, most projects are small enough where they do not benefit from such efficiencies like these. However on the flip side, if you implement two or three of these inefficiencies in the same project, you will start to see issues with delays in time.
In terms of remaining as time efficient as possible, your second approach is probably the most efficient way to handle this, as you are taking two O(n) operations (switching all the elements in the array, and adding a ',' to the end of each) and putting them together into a single operation.
Upvotes: 3