Swift Dictionary Absurd Memory Usage
<p>I ran into an interesting problem in one of my applications. When accessing a <code>Dictionary</code> many times, the memory usage of my application skyrockets to over a gigabyte in seconds. Here is some sample code to show the problem.</p>

<pre><code>override func viewDidLoad() {
        let dictionary = ["key1":"value1"]
        let nsKey: NSString = "key1"
        let swiftKey = nsKey as String
        for _ in 0 ... 10000000 {
            dictionary[swiftKey]
        }
    }
</code></pre>

<p>Repeatedly accessing the dictionary causes memory to climb until the loop finishes. I looked at instruments and saw tons of string allocations. Turns out using an NSString is the issue.</p>

<p>Changing the nsKey to a swift <code>String</code> like so fixes the issue:</p>

<pre><code>let nsKey = "key1"
</code></pre>

<p>Also changing the dictionary to an NSDictionary fixes the issue:</p>

<pre><code>let dictionary: NSDictionary = ["key1":"value1"]
</code></pre>

<p><strong>Does anyone know why accessing the dictionary using a casted NSString causes so much heap allocation, and are there any other fixes besides the ones described above?</strong></p>

<hr>

<p>Here are some pictures. It looks like behind-the-scenes strings are being allocated and set to <em>autorelease</em> (or am I reading the data below wrong?) Could this be why memory usage continuously allocates and then drains at a later point? If this is true, should this be considered a "bug"? This issue occurs on OS X as well as iOS.</p>

<p><a href="https://i.stack.imgur.com/TJfcG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TJfcG.png" alt="enter image description here"></a></p>

<p><a href="https://i.stack.imgur.com/iV8bO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iV8bO.png" alt="enter image description here"></a></p>