swiftstringprocessing-efficiency

Swift: Efficiency considerations of shuffling an array of strings


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?


Solution

  • 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:

    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.