Over a million developers have joined DZone.

Investigating Array Performance in Swift

DZone 's Guide to

Investigating Array Performance in Swift

· Mobile Zone ·
Free Resource

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  vararrayOne : 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 withaddObject() 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).

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}