Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats faster: Insert at index 0 or array.Reverse?

Tags:

swift

reverse

I'm getting data from my database in the reverse order of how I need it to be. In order to correctly order it I have a couple choices: I can insert each new piece of data gotten at index 0 of my array, or just append it then reverse the array at the end. Something like this:

let data = ["data1", "data2", "data3", "data4", "data5", "data6"]
var reversedArray = [String]()

for var item in data {
   reversedArray.insert(item, 0)
}

// OR

reversedArray = data.reverse()

Which one of these options would be faster? Would there be any significant difference between the 2 as the number of items increased?

like image 640
MarksCode Avatar asked Feb 22 '17 15:02

MarksCode


1 Answers

Appending new elements has an amortized complexity of roughly O(1). According to the documentation, reversing an array has also a constant complexity.

Insertion has a complexity O(n), where n is the length of the array and you're inserting all elements one by one.

So appending and then reversing should be faster. But you won't see a noticeable difference if you're only dealing with a few dozen elements.

like image 69
DrummerB Avatar answered Oct 11 '22 08:10

DrummerB