<html><head><style>body{font-family:Helvetica,Arial;font-size:13px}</style></head><body style="word-wrap:break-word"><div id="bloop_customfont" style="font-family:Helvetica,Arial;font-size:13px;color:rgba(0,0,0,1.0);margin:0px;line-height:auto">+1</div> <br> <div id="bloop_sign_1476256035667259904" class="bloop_sign"></div> <br><p class="airmail_on">On October 12, 2016 at 8:54:45 AM, Rien via swift-evolution (<a href="mailto:swift-evolution@swift.org">swift-evolution@swift.org</a>) wrote:</p> <blockquote type="cite" class="clean_bq"><span><div><div></div><div>Beautiful, +1<br><br>Rien<br><br>&gt; On 11 Oct 2016, at 23:28, Nate Cook via swift-evolution &lt;<a href="mailto:swift-evolution@swift.org">swift-evolution@swift.org</a>&gt; wrote:<br>&gt; <br>&gt; Introduction<br>&gt; <br>&gt; This proposal addresses significant unexpected performance gaps when using dictionaries. It introduces type-specific collections for a Dictionary instance&#39;s keys and values properties.<br>&gt; <br>&gt; New DictionaryKeys and DictionaryValues collections provide efficient key lookup and mutable access to dictionary values, enabling updates to be performed in-place and allowing copy-on-write optimization of stored values.<br>&gt; <br>&gt; Motivation<br>&gt; <br>&gt; This proposal address two problems:<br>&gt; <br>&gt;         • The Dictionary type keys implementation is inefficient, because LazyMapCollection doesn&#39;t know how to forward lookups to the underlying dictionary storage.<br>&gt;         • Dictionaries do not offer value-mutating APIs. The mutating key-based subscript wraps values in an Optional. This prevents types with copy-on-write optimizations from recognizing they are singly referenced.<br>&gt; This proposal uses the following [String: [Int]] dictionary to demonstrate these problems:<br>&gt; <br>&gt; var dict = [&quot;one&quot;: [1], &quot;two&quot;: [2, 2], &quot;three&quot;: [3, 3, 3]]<br>&gt; Inefficient dict.keys Search<br>&gt; <br>&gt; Swift coders normally test key membership using nil checks or underscored optional bindings:<br>&gt; <br>&gt; if dict[&quot;one&quot;] != nil<br>&gt;  {<br>&gt;     <br>&gt; // ...<br>&gt; <br>&gt; }<br>&gt; <br>&gt; if let _ = dict[&quot;one&quot;<br>&gt; ] {<br>&gt;     <br>&gt; // ...<br>&gt; <br>&gt; }<br>&gt; <br>&gt; These approaches provide the expected performance of a dictionary lookup but they read neither well nor &quot;Swifty&quot;. Checking keys reads much better but introduces a serious performance penalty: this approach requires a linear search through a dictionary&#39;s keys to find a match.<br>&gt; <br>&gt; if dict.keys.contains(&quot;one&quot;) {<br>&gt;     // ...<br>&gt; }<br>&gt; <br>&gt; A similar dynamic plays out when comparing dict.index(forKey:) and dict.keys.index(of:).<br>&gt; <br>&gt; Inefficient Value Mutation<br>&gt; <br>&gt; Dictionary values can be modified through the keyed subscript by direct reassignment or by using optional chaining. Both of these statements append 1 to the array stored by the key &quot;one&quot;:<br>&gt; <br>&gt; // Direct re-assignment<br>&gt; <br>&gt; dict[<br>&gt; &quot;one&quot;] = (dict[&quot;one&quot;] ?? []) + [1<br>&gt; ]<br>&gt; <br>&gt; <br>&gt; // Optional chaining<br>&gt; <br>&gt; dict[<br>&gt; &quot;one&quot;]?.append(1)<br>&gt; Both approaches present problems. The first is complex and hard to read. The second ignores the case where &quot;one&quot; is not a key in the dictionary. It forces its check into a higher branch and encourages forced unwrapping. Furthermore, neither approach allows the array to grow in place. They introduce an unnecessary copy of the array&#39;s contents even though dict is the sole holder of its storage.<br>&gt; <br>&gt; Adding mutation to a dictionary&#39;s index-based subscripting isn&#39;t possible. Changing a key stored at a particular index would almost certainly modify its hash value, rendering the index incorrect. This violates the requirements of the MutableCollection protocol.<br>&gt; <br>&gt; Proposed Solution<br>&gt; <br>&gt; This proposal adds a custom collection for the keys and values dictionary properties. This follows the example set by String, which presents multiple views of its contents. A new DictionaryKeys collection introduces efficient key lookup, while a new DictionaryValues collection provides a mutable collection interface to dictionary values.<br>&gt; <br>&gt; These changes introduce a simple and efficient way of checking whether a dictionary includes a key:<br>&gt; <br>&gt; // Performant<br>&gt; if dict.keys.contains(&quot;one&quot;<br>&gt; ) {<br>&gt;     <br>&gt; // ...<br>&gt; <br>&gt; }<br>&gt; <br>&gt; As a mutable collection, values enables modification without copies or clumsy code:<br>&gt; <br>&gt; if let i = dict.index(forKey: &quot;one&quot;<br>&gt; ) {<br>&gt;     dict<br>&gt; .values[i].append(1)  // no copy here<br>&gt; <br>&gt; } <br>&gt; else<br>&gt;  {<br>&gt;     dict[<br>&gt; &quot;one&quot;] = [1<br>&gt; ]<br>&gt; }<br>&gt; <br>&gt; Both the keys and values collections share the same index type as Dictionary. This allows the above sample to be rewritten as:<br>&gt; <br>&gt; // Using `dict.keys.index(of:)`<br>&gt; if let i = dict.keys.index(of: &quot;one&quot;<br>&gt; ) {<br>&gt;     dict<br>&gt; .values[i].append(1<br>&gt; )<br>&gt; } <br>&gt; else<br>&gt;  {<br>&gt;     dict[<br>&gt; &quot;one&quot;] = [1<br>&gt; ]<br>&gt; }<br>&gt; <br>&gt; Detailed design<br>&gt; <br>&gt;         • The standard library introduces two new collection types: DictionaryKeys and DictionaryValues.<br>&gt;         • A Dictionary&#39;s keys and values property types change from LazyMapCollection to these new types. <br>&gt;         • The new collection types are not directly constructable. They are presented only as views into a dictionary.<br>&gt; struct Dictionary&lt;Key: Hashable, Value&gt;: ...<br>&gt;  {<br>&gt;     <br>&gt; var keys: DictionaryKeys&lt;Key, Value&gt; { get<br>&gt;  }<br>&gt;     <br>&gt; var values: DictionaryValues&lt;Key, Value&gt; { get set<br>&gt;  }<br>&gt; <br>&gt;     <br>&gt; // Remaining declarations<br>&gt; <br>&gt; }<br>&gt; <br>&gt; <br>&gt; /// A collection view of a dictionary&#39;s keys.<br>&gt; struct DictionaryKeys&lt;Key: Hashable, Value&gt;<br>&gt; : Collection {<br>&gt;     <br>&gt; typealias Index = DictionaryIndex&lt;Key, Value&gt;<br>&gt; <br>&gt;     <br>&gt; subscript(i: Index) -&gt; Key { get<br>&gt;  }<br>&gt; <br>&gt;     <br>&gt; // Other `Collection` requirements<br>&gt; <br>&gt; }<br>&gt; <br>&gt; <br>&gt; /// A mutable collection view of a dictionary&#39;s values.<br>&gt; struct DictionaryValues&lt;Key: Hashable, Value&gt;<br>&gt; : MutableCollection {<br>&gt;     <br>&gt; typealias Index = DictionaryIndex&lt;Key, Value&gt;<br>&gt; <br>&gt;     <br>&gt; subscript(i: Index) -&gt; Value { get set<br>&gt;  }<br>&gt; <br>&gt;     <br>&gt; // Other `Collection` requirements<br>&gt; <br>&gt; }<br>&gt; <br>&gt; A sample implementation of this proposal can be found in this branch.<br>&gt; <br>&gt; Impact on existing code<br>&gt; <br>&gt; The performance improvements of using the new DictionaryKeys type and the mutability of the DictionaryValuescollection are both additive in nature.<br>&gt; <br>&gt; Most uses of these properties are transitory in nature. Adopting this proposal should not produce a major impact on existing code. The only impact on existing code exists where a program explicitly specifies the type of a dictionary&#39;s keysor values property. The fix is to change the specified type. <br>&gt; <br>&gt; Alternatives considered<br>&gt; <br>&gt; The Generics Manifesto lists nested generics as a goal. This could impact the naming and structure of these new collection types. <br>&gt; <br>&gt; Instead of DictionaryKeys&lt;Key, Value&gt; and DictionaryValues&lt;Key, Value&gt;, these types could be Dictionary&lt;Key, Value&gt;.Keys and Dictionary&lt;Key, Value&gt;.Values. However, because many types in the standard library may be revisited once such a feature is available (indices, iterators, etc.), the current lack of nesting shouldn&#39;t prevent consideration of this proposal.<br>&gt; <br>&gt; It could be possible to add additional compiler features that manage mutation through existing key-based subscripting without the copy-on-write problems of the current implementation. I don&#39;t know enough about how that would be implemented to speak to its feasibility or level of effort. Such a feature would reduce the need for a mutable DictionaryValues collection.<br>&gt; _______________________________________________<br>&gt; swift-evolution mailing list<br>&gt; <a href="mailto:swift-evolution@swift.org">swift-evolution@swift.org</a><br>&gt; <a href="https://lists.swift.org/mailman/listinfo/swift-evolution">https://lists.swift.org/mailman/listinfo/swift-evolution</a><br><br>_______________________________________________<br>swift-evolution mailing list<br><a href="mailto:swift-evolution@swift.org">swift-evolution@swift.org</a><br><a href="https://lists.swift.org/mailman/listinfo/swift-evolution">https://lists.swift.org/mailman/listinfo/swift-evolution</a><br></div></div></span></blockquote></body></html>