Over a million developers have joined DZone.

Investigating Array Performance in Swift

· Mobile Zone

Visually compose APIs with easy-to-use tooling. Learn how IBM API Connect provides near-universal access to data and services both on-premises and in the cloud, brought to you in partnership with IBM.

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).

The Mobile Zone is brought to you in partnership with Strongloop and IBM.  Visually compose APIs with easy-to-use tooling. Learn how IBM API Connect provides near-universal access to data and services both on-premises and in the cloud.


Published at DZone with permission of Simon Gladman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}