Quantcast
Channel: FlexMonkey
Viewing all articles
Browse latest Browse all 257

Investigating Array Performance in Swift

$
0
0


I was looking at my Swift Gray Scott application last night and started playing with different ways I could improve the speed of the solvers.

I started tinkering and found some unexpected results:



  • It is quicker to populate the values of an Array by first giving it a length and some arbitrary value (e.g  var arrayOne : Array<Int> = Array<Int>(count: count, repeatedValue : 0); ) and then setting your required value with subscripting than creating an empty array and adding values with append()). 
  • If you are looping over the values of an array, depending on the length of the array, it is often quicker to create a const copy of the array and loop over that. However, in my example project as the array approaches 20,000 items, it's quicker to loop over the original array.
  • NSMutableArray is far, far quicker that Array - even if you have to cast its members - and populating with addObject() is no quicker that using subscripting.
  • The creating a constant copy technique also works for NSMutableArray - but seems to favour larger arrays over smaller ones (i.e. the opposite of Array).

So, the takeaway (for the moment - Swift is still beta so things may well change!) is, if you want to loop over big arrays, use NSMutableArray and loop over a constant copy of it.



I'll be applying these techniques to my Gray Scott experiment tomorrow to see how well it works. In the meantime, my scratch application that I used for timings is available in my Git Hub repository here (the meat is in ViewController.swift).

Stop Press: So, I updated my Gray Scott NSOperation experiment to use NSMutableArray rather than Array and quadrupled the speed! One thing to note is that NSMutableArray doesn't like tuples, so I had to create a new class, GrayScottStruct which implements GrayScottProtocol. The protocol needs an @objc attribute to work with NSMutableArray.

The source is updated and available here.




Viewing all articles
Browse latest Browse all 257

Trending Articles