<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:media="http://search.yahoo.com/mrss/"
>

<channel>
	<title>Fibonacci &#8211; Wade Tregaskis</title>
	<atom:link href="https://wadetregaskis.com/tags/fibonacci/feed/" rel="self" type="application/rss+xml" />
	<link>https://wadetregaskis.com</link>
	<description></description>
	<lastBuildDate>Wed, 15 May 2024 05:42:34 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://wadetregaskis.com/wp-content/uploads/2016/03/Stitch-512x512-1-256x256.png</url>
	<title>Fibonacci &#8211; Wade Tregaskis</title>
	<link>https://wadetregaskis.com</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">226351702</site>	<item>
		<title>Swift tip: the swap function</title>
		<link>https://wadetregaskis.com/swift-tip-the-swap-function/</link>
					<comments>https://wadetregaskis.com/swift-tip-the-swap-function/#respond</comments>
		
		<dc:creator><![CDATA[]]></dc:creator>
		<pubDate>Tue, 14 May 2024 23:43:20 +0000</pubDate>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[Fibonacci]]></category>
		<category><![CDATA[MutableCollection]]></category>
		<category><![CDATA[swap]]></category>
		<category><![CDATA[swapAt]]></category>
		<category><![CDATA[Swift]]></category>
		<guid isPermaLink="false">https://wadetregaskis.com/?p=8079</guid>

					<description><![CDATA[The following code prints the Fibonacci sequence. You&#8217;ve probably seen it before. It&#8217;s one of the simplest and most well-known examples of a sliding window operation &#8211; where the next value depends on the preceding two (or more) values. While almost all programs do not calculate the Fibonacci sequence, many do contain similar sliding-window algorithms.&#8230; <a class="read-more-link" href="https://wadetregaskis.com/swift-tip-the-swap-function/" data-wpel-link="internal">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p>The following code prints the Fibonacci sequence. You&#8217;ve probably seen it before. It&#8217;s one of the simplest and most well-known examples of a sliding window operation &#8211; where the next value depends on the preceding two (or more) values. While almost all programs do <em>not</em> calculate the Fibonacci sequence, many do contain similar sliding-window algorithms. And code that uses the <code><a href="https://developer.apple.com/documentation/swift/array/reduce(_:_:)" data-wpel-link="external" target="_blank" rel="external noopener">reduce(_:_:)</a></code> / <code><a href="https://developer.apple.com/documentation/swift/array/reduce(into:_:)" data-wpel-link="external" target="_blank" rel="external noopener">reduce(into:_:)</a></code> methods is usually doing a similar thing, too.</p>



<div class="wp-block-kevinbatdorf-code-block-pro padding-disabled" data-code-block-pro-font-family="" style="font-size:.875rem;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><pre class="shiki light-plus" style="background-color: #FFFFFF" tabindex="0"><code><span class="line"><span style="color: #0000FF">var</span><span style="color: #000000"> previous = </span><span style="color: #795E26">UIntXL</span><span style="color: #000000">(</span><span style="color: #098658">0</span><span style="color: #000000">)</span></span>
<span class="line"><span style="color: #0000FF">var</span><span style="color: #000000"> current = </span><span style="color: #795E26">UIntXL</span><span style="color: #000000">(</span><span style="color: #098658">1</span><span style="color: #000000">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #795E26">print</span><span style="color: #000000">(previous)</span></span>
<span class="line"><span style="color: #795E26">print</span><span style="color: #000000">(current)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #AF00DB">while</span><span style="color: #000000"> </span><span style="color: #0000FF">true</span><span style="color: #000000"> {</span></span>
<span class="line"><span style="color: #000000">    </span><span style="color: #0000FF">let</span><span style="color: #000000"> next = previous + current</span></span>
<span class="line"><span style="color: #000000">    previous = current</span></span>
<span class="line"><span style="color: #000000">    current = next</span></span>
<span class="line"></span>
<span class="line"><span style="color: #000000">    </span><span style="color: #795E26">print</span><span style="color: #000000">(next)</span></span>
<span class="line"><span style="color: #000000">}</span></span></code></pre></div>



<p>Short of using a different algorithm entirely (there are <a href="https://r-knott.surrey.ac.uk/Fibonacci/fibFormula.html" data-wpel-link="external" target="_blank" rel="external noopener">much smarter ways to calculate Fibonacci numbers</a>), you&#8217;d think it&#8217;d be optimally fast &#8211; I mean, how can the above example get any better, really?</p>



<p>Well, by doing this:</p>



<div class="wp-block-kevinbatdorf-code-block-pro padding-disabled" data-code-block-pro-font-family="" style="font-size:.875rem;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><pre class="shiki light-plus" style="background-color: #FFFFFF" tabindex="0"><code><span class="line"><span style="color: #0000FF">var</span><span style="color: #000000"> previous = </span><span style="color: #795E26">UIntXL</span><span style="color: #000000">(</span><span style="color: #098658">0</span><span style="color: #000000">)</span></span>
<span class="line"><span style="color: #0000FF">var</span><span style="color: #000000"> current = </span><span style="color: #795E26">UIntXL</span><span style="color: #000000">(</span><span style="color: #098658">1</span><span style="color: #000000">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #795E26">print</span><span style="color: #000000">(previous)</span></span>
<span class="line"><span style="color: #795E26">print</span><span style="color: #000000">(current)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #AF00DB">while</span><span style="color: #000000"> </span><span style="color: #0000FF">true</span><span style="color: #000000"> {</span></span>
<span class="line"><span style="color: #000000">    previous += current</span></span>
<span class="line"><span style="color: #000000">    </span><span style="color: #795E26">swap</span><span style="color: #000000">(&amp;previous, &amp;current)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #000000">    </span><span style="color: #795E26">print</span><span style="color: #000000">(next)</span></span>
<span class="line"><span style="color: #000000">}</span></span></code></pre></div>



<p>Sometimes this version is significantly faster (e.g. <a href="https://forums.swift.org/t/standard-vapor-website-drops-1-5-of-requests-even-at-concurrency-of-100/71583/73" data-wpel-link="external" target="_blank" rel="external noopener">30% in a recent example</a>, and I&#8217;ve seen up to 14x in some of my own, similar cases).</p>



<p>Admittedly, sometimes it&#8217;s merely as fast &#8211; sometimes the Swift compiler optimises the first version into the second for us. But the compiler&#8217;s optimiser is unreliable and unpredictable. So if performance is important to you, it&#8217;s best to use <code>swap</code> explicitly rather than hang your hopes on the compiler.</p>



<h2 class="wp-block-heading">What does <code><a href="https://developer.apple.com/documentation/swift/swap(_:_:)" data-wpel-link="external" target="_blank" rel="external noopener">swap</a></code> do?</h2>



<p>Its purpose is pretty obvious &#8211; it swaps the contents of two variables. <em>Logically</em> it&#8217;s equivalent to<sup data-fn="3245c9e9-e853-452f-9f59-1821ed0d19bc" class="fn"><a href="#3245c9e9-e853-452f-9f59-1821ed0d19bc" id="3245c9e9-e853-452f-9f59-1821ed0d19bc-link">1</a></sup>:</p>



<div class="wp-block-kevinbatdorf-code-block-pro padding-disabled" data-code-block-pro-font-family="" style="font-size:.875rem;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="func swap(_ a: inout T, _ b: inout T) {
    let tmp = a
    a = b
    b = tmp
}" style="color:#000000;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki light-plus" style="background-color: #FFFFFF" tabindex="0"><code><span class="line"><span style="color: #0000FF">func</span><span style="color: #000000"> </span><span style="color: #795E26">swap</span><span style="color: #000000">(</span><span style="color: #795E26">_</span><span style="color: #000000"> </span><span style="color: #001080">a</span><span style="color: #000000">: </span><span style="color: #0000FF">inout</span><span style="color: #000000"> T, </span><span style="color: #795E26">_</span><span style="color: #000000"> </span><span style="color: #001080">b</span><span style="color: #000000">: </span><span style="color: #0000FF">inout</span><span style="color: #000000"> T) {</span></span>
<span class="line"><span style="color: #000000">    </span><span style="color: #0000FF">let</span><span style="color: #000000"> tmp = a</span></span>
<span class="line"><span style="color: #000000">    a = b</span></span>
<span class="line"><span style="color: #000000">    b = tmp</span></span>
<span class="line"><span style="color: #000000">}</span></span></code></pre></div>



<p>But that&#8217;s <em>not</em> how it&#8217;s actually implemented. The implementation starts <a href="https://github.com/apple/swift/blob/c1597154a935b0f61646c5accb79a45ce470f944/stdlib/public/core/MutableCollection.swift#L531" data-wpel-link="external" target="_blank" rel="external noopener">here</a>, though the pertinent details are hidden behind compiler built-ins. Suffice to know that it boils down to <em>simply swapping the raw bytes</em>.</p>



<h2 class="wp-block-heading">Why is that better?</h2>



<p>It avoids unnecessary work: temporary object initialisation and deinitialisation, memory allocation (and frees), reference-counting, etc.  That can be from the more efficient swap itself, and/or from mutating one of the values in place rather than creating a temporary third value.</p>



<p>It can also prevent unnecessary copy-on-write behaviour, if you&#8217;re mixing the swap in amongst other mutations on value types that implement reference semantics<sup data-fn="c5986145-3ce7-4086-ade3-ef670ccba9d1" class="fn"><a href="#c5986145-3ce7-4086-ade3-ef670ccba9d1" id="c5986145-3ce7-4086-ade3-ef670ccba9d1-link">2</a></sup> (like the standard <code>Array</code>, <code>Set</code>, etc).  That usually saves time but can also, in some relatively rare circumstances, save memory too (by not leaving duplicate copies of internal buffers in memory indefinitely).</p>



<p>It also works for <code><a href="https://github.com/apple/swift-evolution/blob/main/proposals/0390-noncopyable-structs-and-enums.md" data-wpel-link="external" target="_blank" rel="external noopener">~Copyable</a></code> types without any extra effort.</p>



<h2 class="wp-block-heading">Is it always optimal?</h2>



<p>For <em>actually</em> swapping two values in RAM, <s>yes</s>.</p>



<p>Well, maybe.  Mostly?  It turns out &#8211; after I initially published this post &#8211; that it&#8217;s a bit more complicated than that.  <em>Sometimes</em> an alternative method is slightly faster:  the &#8220;tuple swap&#8221;.  e.g.:</p>



<div class="wp-block-kevinbatdorf-code-block-pro padding-disabled" data-code-block-pro-font-family="" style="font-size:.875rem;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span role="button" tabindex="0" data-code="var previous = UIntXL(0)
var current = UIntXL(1)

print(previous)
print(current)

while true {
    previous += current
    (previous, current) = (current, previous)

    print(next)
}" style="color:#000000;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki light-plus" style="background-color: #FFFFFF" tabindex="0"><code><span class="line"><span style="color: #0000FF">var</span><span style="color: #000000"> previous = </span><span style="color: #795E26">UIntXL</span><span style="color: #000000">(</span><span style="color: #098658">0</span><span style="color: #000000">)</span></span>
<span class="line"><span style="color: #0000FF">var</span><span style="color: #000000"> current = </span><span style="color: #795E26">UIntXL</span><span style="color: #000000">(</span><span style="color: #098658">1</span><span style="color: #000000">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #795E26">print</span><span style="color: #000000">(previous)</span></span>
<span class="line"><span style="color: #795E26">print</span><span style="color: #000000">(current)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #AF00DB">while</span><span style="color: #000000"> </span><span style="color: #0000FF">true</span><span style="color: #000000"> {</span></span>
<span class="line"><span style="color: #000000">    previous += current</span></span>
<span class="line"><span style="color: #000000">    (previous, current) = (current, previous)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #000000">    </span><span style="color: #795E26">print</span><span style="color: #000000">(next)</span></span>
<span class="line"><span style="color: #000000">}</span></span></code></pre></div>



<p>In <em>some</em> benchmarks that&#8217;s faster, in some it&#8217;s slower<sup data-fn="f4e9238d-e4d4-416f-90d2-369fd82972bb" class="fn"><a href="#f4e9238d-e4d4-416f-90d2-369fd82972bb" id="f4e9238d-e4d4-416f-90d2-369fd82972bb-link">3</a></sup>. It <em>seems</em> to always be faster than using a named temporary, just like <code>swap</code>, although I don&#8217;t believe that&#8217;s guaranteed behaviour. Furthermore, it relies on the compiler successfully recognising that particular expression of the swap intent and optimising it appropriately. Plus, using <code>swap</code> is shorter, clearer, and less error-prone. So I think an explicit call to <code>swap</code> is still the best option.</p>



<p>In any case, there are sometimes faster methods which eliminate the need to actually swap the bytes around. e.g. using a pointer to toggle between the two values. To my knowledge, Swift doesn&#8217;t provide any way to actually do that for value types, since Swift tries to pretend that pointers don&#8217;t exist for them. 😔</p>



<p>Hypothetically the optimiser could perform that optimisation for any code like the above examples, and others, although I&#8217;ve never seen it do that.</p>



<hr class="wp-block-separator has-alpha-channel-opacity is-style-dots"/>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained">
<p>☝️ <code>swap</code> has a cousin, <code><a href="https://developer.apple.com/documentation/swift/mutablecollection/swapat(_:_:)-8f65z" data-wpel-link="external" target="_blank" rel="external noopener">swapAt</a></code>, on <code><a href="https://developer.apple.com/documentation/swift/mutablecollection" data-wpel-link="external" target="_blank" rel="external noopener">MutableCollection</a></code>s. It&#8217;s even <em>less</em> known than <code>swap</code>, but it&#8217;s potentially even more frequently useful in general code. Its purpose is to likewise ensure that swapping two elements within the same collection is as efficient as possible, irrespective of how the compiler is feeling that day.</p>



<p>But, bizarrely, <a href="https://github.com/apple/swift/blob/c1597154a935b0f61646c5accb79a45ce470f944/stdlib/public/core/MutableCollection.swift#L320" data-wpel-link="external" target="_blank" rel="external noopener">its implementation</a> does <em>not</em> use <code>swap</code> or otherwise contain the same guaranteed optimisations. So it might <em>not</em> be the fastest way to swap two elements. 😕</p>



<p>It might be an unfortunate consequence of Swift&#8217;s exclusive access checking &#8211; specifically its lack of support for non-overlapping access within a collection &#8211; because if you do try to use <code>swap</code> yourself on the elements of a collection, the compiler refuses it:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><code>❌ Overlapping accesses to 'x', but modification requires exclusive access; consider calling MutableCollection.swapAt(_:_:)</code></p>
</blockquote>
</div></div>


<ol class="wp-block-footnotes"><li id="3245c9e9-e853-452f-9f59-1821ed0d19bc">Ignoring support for <a href="https://github.com/apple/swift-evolution/blob/main/proposals/0390-noncopyable-structs-and-enums.md" data-wpel-link="external" target="_blank" rel="external noopener">~Copyable</a> types, which can be done but requires a more complicated implementation than we need to worry about here. <a href="#3245c9e9-e853-452f-9f59-1821ed0d19bc-link" aria-label="Jump to footnote reference 1">↩︎</a></li><li id="c5986145-3ce7-4086-ade3-ef670ccba9d1">Many value types in Swift are <em>not</em> actually just simple sequences of bytes.  They often contain pointers to potentially-shared <em>reference</em> objects (e.g. classes or actors), or raw memory buffers.  When you copy the value &#8211; which includes simply assigning it to a new variable &#8211; there can be a lot of work involved in incrementing reference counts for these now-shared internal objects &amp; buffers (which also means time spent decrementing those counts some time later).<br><br>And that&#8217;s assuming a type that uses copy-on-write (or similar) optimisations &#8211; otherwise, you&#8217;re going to have to copy all those internal memory buffers as well, which can be tremendously expensive.<br><br>Even mere reference counting operations are actually pretty expensive &#8211; tens to hundreds of instructions each, typically.  <em>Usually</em> in Swift we don&#8217;t notice them because the optimiser works very hard to actually remove them, as much as possible. <a href="#c5986145-3ce7-4086-ade3-ef670ccba9d1-link" aria-label="Jump to footnote reference 2">↩︎</a></li><li id="f4e9238d-e4d4-416f-90d2-369fd82972bb">I put together <a href="https://github.com/wadetregaskis/Swift-Benchmarks/blob/main/Benchmarks/Swap/Swap.swift" data-wpel-link="external" target="_blank" rel="external noopener">some benchmarks</a> in researching &amp; writing this post, with the intent of using them as specific examples of the performance differences.  Unfortunately they are apparently too simple, and the optimiser is generally able to optimise the named temporary method into using <code>swap</code> or the &#8220;tuple swap&#8221; method (even though in real-world code it usually fails to do so, in my experience). <a href="#f4e9238d-e4d4-416f-90d2-369fd82972bb-link" aria-label="Jump to footnote reference 3">↩︎</a></li></ol>]]></content:encoded>
					
					<wfw:commentRss>https://wadetregaskis.com/swift-tip-the-swap-function/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">8079</post-id>	</item>
	</channel>
</rss>
