{"id":1910,"date":"2015-08-15T14:36:21","date_gmt":"2015-08-15T20:36:21","guid":{"rendered":"http:\/\/jamesonquave.com\/blog\/?p=1910"},"modified":"2015-08-15T15:28:50","modified_gmt":"2015-08-15T21:28:50","slug":"list-comprehensions-and-performance-with-swift","status":"publish","type":"post","link":"https:\/\/jamesonquave.com\/blog\/list-comprehensions-and-performance-with-swift\/","title":{"rendered":"List Comprehensions and Performance With Swift"},"content":{"rendered":"<p><b><i>This post written on August 15, 2015 to be compatible with Xcode 6 and Swift 1.2<\/i><\/b><\/p>\n<p>List comprehensions provide a concise way to create lists. You can accomplish list comprehension-like operations in Swift even though list comprehensions are not mentioned in the Swift language guide. <\/p>\n<p>Say you want to create a list of squares, like:<\/p>\n<pre><code><div id=\"highlighter_302435\" class=\"syntaxhighlighter nogutter highlightedCode \"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td class=\"code\"><div class=\"container\"><div class=\"line number1 index0 alt2\"><code class=\"keyword\">var<\/code> <code class=\"plain\">squares = [<\/code><code class=\"color1\">Int<\/code><code class=\"plain\">]()<\/code><\/div><div class=\"line number2 index1 alt1\"><code class=\"keyword\">for<\/code> <code class=\"plain\">x <\/code><code class=\"keyword\">in<\/code> <code class=\"plain\">1..<10 {<\/code><\/div><div class=\"line number3 index2 alt2\"><code class=\"plain\">&nbsp;&nbsp;&nbsp;&nbsp;squares.append(x*x)<\/code><\/div><div class=\"line number4 index3 alt1\"><code class=\"plain\">}<\/code><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/code><\/pre>\n<p>In Python you could use a list comprehension instead<\/p>\n<pre><code><div id=\"highlighter_455438\" class=\"syntaxhighlighter nogutter highlightedCode \"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td class=\"code\"><div class=\"container\"><div class=\"line number1 index0 alt2\"><code class=\"plain\">squares = [x**2 <\/code><code class=\"keyword\">for<\/code> <code class=\"plain\">x <\/code><code class=\"keyword\">in<\/code> <code class=\"plain\">range(10)]<\/code><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/code><\/pre>\n<p>In Swift you can do<\/p>\n<pre><code><div id=\"highlighter_139849\" class=\"syntaxhighlighter nogutter highlightedCode \"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td class=\"code\"><div class=\"container\"><div class=\"line number1 index0 alt2\"><code class=\"keyword\">let<\/code> <code class=\"plain\">squares = <\/code><code class=\"color2\">Array<\/code><code class=\"plain\">(<\/code><code class=\"functions\">map<\/code><code class=\"plain\">(1..&lt;10) { $0 * $0 })<\/code><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/code><\/pre>\n<p>To get the sum of all the elements in the list you could do this<\/p>\n<pre><code><div id=\"highlighter_547605\" class=\"syntaxhighlighter nogutter highlightedCode \"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td class=\"code\"><div class=\"container\"><div class=\"line number1 index0 alt2\"><code class=\"keyword\">var<\/code> <code class=\"plain\">sum = 0<\/code><\/div><div class=\"line number2 index1 alt1\"><code class=\"keyword\">for<\/code> <code class=\"plain\">square <\/code><code class=\"keyword\">in<\/code> <code class=\"plain\">squares {<\/code><\/div><div class=\"line number3 index2 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"plain\">sum = sum + square<\/code><\/div><div class=\"line number4 index3 alt1\"><code class=\"plain\">}<\/code><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/code><\/pre>\n<p>Or use the reduce function<\/p>\n<pre><code><div id=\"highlighter_190590\" class=\"syntaxhighlighter nogutter highlightedCode \"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td class=\"code\"><div class=\"container\"><div class=\"line number1 index0 alt2\"><code class=\"keyword\">let<\/code> <code class=\"plain\">sum = squares.reduce(0, { $0 + $1 })<\/code><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/code><\/pre>\n<p>Like list comprehensions in some other languages, you can use any Sequence or Collection as the input, not just a Range.<\/p>\n<p><a href=\"http:\/\/stackoverflow.com\/questions\/24003584\/list-comprehension-in-swift\">You can use map\/reduce\/filter\/stride depending on what kind of list you are trying to create.<\/a><\/p>\n<p>The two main perks of list comprehensions are conciseness and being able to generate faster bitcode. <\/p>\n<p>My imitation list comprehension was more concise. I was curious whether it would also generate faster bitcode.<\/p>\n<p><a href=\"https:\/\/medium.com\/swift-programming\/secret-of-swift-performance-fcc5d2a437a8\">This article<\/a> showed me how to analyze Swift assembly code using Hopper, an OSX and Linux disassembler. You can try Hopper for free without buying a license. <\/p>\n<p>The code snippets without list comprehensions and with the imitation list comprehensions generated the same assembly code. <\/p>\n<p><img decoding=\"async\" src=\"http:\/\/jamesonquave.com\/tutImg\/asm.png\" alt=\"The assembly code from Hopper\"><\/p>\n<p>Since both snippets created the same assembly code I assumed their execution time would be the same. We can demontrate this by measuring the execution of our program using XCTest. <\/p>\n<p>My test for the code snippet with no list comprehension<\/p>\n<pre><code><div id=\"highlighter_662601\" class=\"syntaxhighlighter nogutter highlightedCode \"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td class=\"code\"><div class=\"container\"><div class=\"line number1 index0 alt2\"><code class=\"keyword\">func<\/code> <code class=\"plain\">testNoListComprehensionPerformance() {<\/code><\/div><div class=\"line number2 index1 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">self<\/code><code class=\"plain\">.measureBlock() {<\/code><\/div><div class=\"line number3 index2 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">var<\/code> <code class=\"plain\">squares = [<\/code><code class=\"color1\">Int<\/code><code class=\"plain\">]()<\/code><\/div><div class=\"line number4 index3 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"keyword\">for<\/code> <code class=\"plain\">x <\/code><code class=\"keyword\">in<\/code> <code class=\"plain\">1...5 {<\/code><\/div><div class=\"line number5 index4 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"plain\">squares.append(x)<\/code><\/div><div class=\"line number6 index5 alt1\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"plain\">}<\/code><\/div><div class=\"line number7 index6 alt2\"><code class=\"undefined spaces\">&nbsp;&nbsp;&nbsp;&nbsp;<\/code><code class=\"plain\">}<\/code><\/div><div class=\"line number8 index7 alt1\"><code class=\"plain\">}<\/code><\/div><\/div><\/td><\/tr><\/tbody><\/table><\/div><\/code><\/pre>\n<p>The relevant output<\/p>\n<p>Test Case '-[speedTestTests.speedTestTests testNoListComprehensionPerformance]' started.<\/p>\n<p><unknown>:0: Test Case '-[speedTestTests.speedTestTests testNoListComprehensionPerformance]' measured [Time, seconds] average: 0.000, relative standard deviation: 236.965%, values: [0.000154, 0.000005, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004], performanceMetricID:com.apple.XCTPerformanceMetric_WallClockTime, baselineName: \"\", baselineAverage: , maxPercentRegression: 10.000%, maxPercentRelativeStandardDeviation: 10.000%, maxRegression: 0.100, maxStandardDeviation: 0.100<br \/>\nTest Case '-[speedTestTests.speedTestTests testNoListComprehensionPerformance]' passed (0.262 seconds).<\/unknown><\/p>\n<p>My test for the code snippet with the imitation list comprehension<\/p>\n<p>Test Case '-[speedTestTests.speedTestTests testSortaListComprehensionPerformance]' started.<\/p>\n<p><unknown>:0: Test Case '-[speedTestTests.speedTestTests testSortaListComprehensionPerformance]' measured [Time, seconds] average: 0.000, relative standard deviation: 160.077%, values: [0.000045, 0.000005, 0.000004, 0.000003, 0.000003, 0.000003, 0.000003, 0.000004, 0.000003, 0.000003], performanceMetricID:com.apple.XCTPerformanceMetric_WallClockTime, baselineName: \"\", baselineAverage: , maxPercentRegression: 10.000%, maxPercentRelativeStandardDeviation: 10.000%, maxRegression: 0.100, maxStandardDeviation: 0.100<br \/>\nTest Case '-[speedTestTests.speedTestTests testSortaListComprehensionPerformance]' passed (0.255 seconds).<\/unknown><\/p>\n<p><strong><\/p>\n<p>On average they only differ by only 0.007 seconds. <\/p>\n<p><\/strong><\/p>\n<p>The coolest application of list comprehensions I've seen is in a spelling corrector. <a href=\"http:\/\/airspeedvelocity.net\/2015\/05\/02\/spelling\/\">Airspeed Velocity wrote a Swift version<\/a> of <a href=\"http:\/\/norvig.com\/spell-correct.html\">Peter Norvig's Python spelling corrector<\/a>. <\/p>\n<p>Conciseness is the main benefit of using list comprehension-like operations in Swift. <a href=\"http:\/\/www.paulgraham.com\/power.html\">Paul Graham wrote a great essay about how conciseness in programming languages is power.<\/a> Since each programmer can only write a certain number of lines of code per day, you can accomplish more each day if you can accomplish more in the same number of lines. This power also makes you rethink what programs are possible. In a more verbose language this spelling corrector example could have seemed like an overwhelming project. I love how how something as technically complex and mysterious as a spelling corrector can be expressed in so few lines of code in Swift. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>This post written on August 15, 2015 to be compatible with Xcode 6 and Swift 1.2 List comprehensions provide a concise way to create lists. You can accomplish list comprehension-like operations in Swift even though list comprehensions are not mentioned in the Swift language guide. Say you want to create a list of squares, like:&#8230;<\/p>\n","protected":false},"author":7,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_links_to":"","_links_to_target":""},"categories":[70,50,26,10,32],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v19.13 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>List Comprehensions and Performance With Swift - Jameson Quave<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jamesonquave.com\/blog\/list-comprehensions-and-performance-with-swift\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"List Comprehensions and Performance With Swift - Jameson Quave\" \/>\n<meta property=\"og:description\" content=\"This post written on August 15, 2015 to be compatible with Xcode 6 and Swift 1.2 List comprehensions provide a concise way to create lists. You can accomplish list comprehension-like operations in Swift even though list comprehensions are not mentioned in the Swift language guide. Say you want to create a list of squares, like:...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jamesonquave.com\/blog\/list-comprehensions-and-performance-with-swift\/\" \/>\n<meta property=\"og:site_name\" content=\"Jameson Quave\" \/>\n<meta property=\"article:published_time\" content=\"2015-08-15T20:36:21+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2015-08-15T21:28:50+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/jamesonquave.com\/tutImg\/asm.png\" \/>\n<meta name=\"author\" content=\"Veronica Ray\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Veronica Ray\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/list-comprehensions-and-performance-with-swift\/\",\"url\":\"https:\/\/jamesonquave.com\/blog\/list-comprehensions-and-performance-with-swift\/\",\"name\":\"List Comprehensions and Performance With Swift - Jameson Quave\",\"isPartOf\":{\"@id\":\"https:\/\/jamesonquave.com\/blog\/#website\"},\"datePublished\":\"2015-08-15T20:36:21+00:00\",\"dateModified\":\"2015-08-15T21:28:50+00:00\",\"author\":{\"@id\":\"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/2bbd3e72c3814506529f54f4e76b1410\"},\"breadcrumb\":{\"@id\":\"https:\/\/jamesonquave.com\/blog\/list-comprehensions-and-performance-with-swift\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jamesonquave.com\/blog\/list-comprehensions-and-performance-with-swift\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/list-comprehensions-and-performance-with-swift\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jamesonquave.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"List Comprehensions and Performance With Swift\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/#website\",\"url\":\"https:\/\/jamesonquave.com\/blog\/\",\"name\":\"Jameson Quave\",\"description\":\"Using computer technology to educate, and improve lives.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jamesonquave.com\/blog\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/2bbd3e72c3814506529f54f4e76b1410\",\"name\":\"Veronica Ray\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/88f918657885742a324bf0e38203256f?s=96&d=retro&r=pg\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/88f918657885742a324bf0e38203256f?s=96&d=retro&r=pg\",\"caption\":\"Veronica Ray\"},\"description\":\"Veronica Ray is a software engineer at LinkedIn. She honed her functional programming chops in Scala and is excited about developing on iOS with Swift. Once she rode her bike between two moose. Follow her on Medium and Twitter: @nerdonica.\",\"sameAs\":[\"https:\/\/medium.com\/@nerdonica\"],\"url\":\"https:\/\/jamesonquave.com\/blog\/author\/nerdonica\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"List Comprehensions and Performance With Swift - Jameson Quave","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jamesonquave.com\/blog\/list-comprehensions-and-performance-with-swift\/","og_locale":"en_US","og_type":"article","og_title":"List Comprehensions and Performance With Swift - Jameson Quave","og_description":"This post written on August 15, 2015 to be compatible with Xcode 6 and Swift 1.2 List comprehensions provide a concise way to create lists. You can accomplish list comprehension-like operations in Swift even though list comprehensions are not mentioned in the Swift language guide. Say you want to create a list of squares, like:...","og_url":"https:\/\/jamesonquave.com\/blog\/list-comprehensions-and-performance-with-swift\/","og_site_name":"Jameson Quave","article_published_time":"2015-08-15T20:36:21+00:00","article_modified_time":"2015-08-15T21:28:50+00:00","og_image":[{"url":"http:\/\/jamesonquave.com\/tutImg\/asm.png"}],"author":"Veronica Ray","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Veronica Ray"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/jamesonquave.com\/blog\/list-comprehensions-and-performance-with-swift\/","url":"https:\/\/jamesonquave.com\/blog\/list-comprehensions-and-performance-with-swift\/","name":"List Comprehensions and Performance With Swift - Jameson Quave","isPartOf":{"@id":"https:\/\/jamesonquave.com\/blog\/#website"},"datePublished":"2015-08-15T20:36:21+00:00","dateModified":"2015-08-15T21:28:50+00:00","author":{"@id":"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/2bbd3e72c3814506529f54f4e76b1410"},"breadcrumb":{"@id":"https:\/\/jamesonquave.com\/blog\/list-comprehensions-and-performance-with-swift\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jamesonquave.com\/blog\/list-comprehensions-and-performance-with-swift\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jamesonquave.com\/blog\/list-comprehensions-and-performance-with-swift\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jamesonquave.com\/blog\/"},{"@type":"ListItem","position":2,"name":"List Comprehensions and Performance With Swift"}]},{"@type":"WebSite","@id":"https:\/\/jamesonquave.com\/blog\/#website","url":"https:\/\/jamesonquave.com\/blog\/","name":"Jameson Quave","description":"Using computer technology to educate, and improve lives.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jamesonquave.com\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/2bbd3e72c3814506529f54f4e76b1410","name":"Veronica Ray","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/88f918657885742a324bf0e38203256f?s=96&d=retro&r=pg","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/88f918657885742a324bf0e38203256f?s=96&d=retro&r=pg","caption":"Veronica Ray"},"description":"Veronica Ray is a software engineer at LinkedIn. She honed her functional programming chops in Scala and is excited about developing on iOS with Swift. Once she rode her bike between two moose. Follow her on Medium and Twitter: @nerdonica.","sameAs":["https:\/\/medium.com\/@nerdonica"],"url":"https:\/\/jamesonquave.com\/blog\/author\/nerdonica\/"}]}},"_links":{"self":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts\/1910"}],"collection":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/comments?post=1910"}],"version-history":[{"count":10,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts\/1910\/revisions"}],"predecessor-version":[{"id":1920,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts\/1910\/revisions\/1920"}],"wp:attachment":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/media?parent=1910"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/categories?post=1910"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/tags?post=1910"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}