Swift: Efficiency considerations of shuffling an array of strings

84 Views Asked by At

If I have an array of strings ["xyz", "def", ...] in Swift how is this list stored?

My plan is to shuffle this array by transposing random pairs of elements.

Does the array contain a list of pointers to the Strings which I can just swap at minimal cost?

In other words if I shuffle the array in this way, will it just swap the pointers or will this approach cause it to copy the strings?

2

There are 2 best solutions below

6
Alexander On BEST ANSWER

Is there a reason not to use the built-in Array.shuffled()? You can implement your own Fisher-Yates or whatever, but the built-in one is simple, well-optimized, and well, built-in!

let fruits = ["apple", "banana", "cherry"]
print(fruits.shuffled())

In your own algorithms, you can use Array.swapAt(_:_:) to swap the elements at any two indices in an array.

Storage details

For your own curiousity, I'll give a bit of detail on how these things are stored. For Arrays and Strings... its complicated. Both are open source, so you can see for yourself:

Each of them multiple storage strategies to optimize certain cases. For example:

  • Array can be backed by an NSArray for fast, copy-less bridging to-from Objective-C.
  • Likewise for String and NSString.
  • Native Swift Arrays store structs like strings directly inline in a contiguous buffer.

Strings are currently usually a 16 byte struct that contains a pointer to a heap-allocated storage. There's a small-string optimization that forgoes that heap allocation, if the string content is 15 bytes or less, where it will just store it directly inline.

0
Cy-4AH On

You can look with "jump to definition" that Strings and Arrays are Struct. They are value types. But it doesn't mean that they storing all content in the stack, they have pointer inside that pointing to heap. You can think of them as smart pointers. If task to work with large memory and performance is significantly important, then better to look for more low level programming language.