Developer’s Library ESSENTIAL REFERENCES FOR PROGRAMMING PROFESSIONALS Opened in November 2010, the Sheikh Zayed Bridge offers a stunning entryway to the city of Abu Dhabi, United Arab Emirates. Designed by the visionary architect Zaha Hadid, the bridge appears to onlookers as a series of rising and falling concrete waves, reminiscent of the region’s nearby sand dunes. Hadid’s “waves,” reaching 64 meters at their peak, appear to propel Shell Programming in Unix, Mastering iOS Frameworks: The Gourmet iOS themselves toward the city. Her design’s extraordinary Linux and OS X, Beyond the Basics, Developer’s Cookbook Fourth Edition Second Edition energy is reinforced by dynamic nighttime lighting, Erica Sadun making the bridge an unforgettable local landmark. Stephen G. Kochan Kyle Richter ISBN-13: 978-0-13-408622-4 Patrick Wood Joe Keeley ISBN-13: 978-0-13-449600-9 ISBN-13: 978-0-13-405249-6 Other Developer’s Library Titles TITLE AUTHOR ISBN-13 The Swift Developer’s Cookbook Erica Sadun 978-0-13-439526-5 Test-Driven iOS Graham Lee 978-0-321-77418-7 Development Cocoa®Programming David Chisnall 978-0-321-63963-9 Developer’s Handbook Cocoa Design Patterns Erik M. Buck / Donald A. Yacktman 978-0-321-53502-3 Developer’s Library books are available at most retail and online bookstores. For more information or to order direct, visit our online bookstore at informit.com/store Developer’s Library Online editions of all Developer’s Library titles are available by subscription from Safari Books Online at safari.informit.com informit.com/devlibrary 9780321842848_Weiher_Swift_Cocoa_OC_Perform_Tuning_Cover.indd 2 2/2/17 11:05 AM iOS and macOS™ Performance Tuning This page intentionally left blank iOS and macOS™ Performance Tuning Cocoa®, Cocoa Touch®, Objective-C®, and Swift™ Marcel Weiher Boston(cid:15)Columbus(cid:15)Indianapolis(cid:15)NewYork(cid:15)SanFrancisco(cid:15)Amsterdam(cid:15)CapeTown Dubai(cid:15)London(cid:15)Madrid(cid:15)Milan(cid:15)Munich(cid:15)Paris(cid:15)Montreal(cid:15)Toronto(cid:15)Delhi(cid:15)MexicoCity SãoPaulo(cid:15)Sydney(cid:15)HongKong(cid:15)Seoul(cid:15)Singapore(cid:15)Taipei(cid:15)Tokyo Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheir Editor-in-Chief productsareclaimedastrademarks.Wherethosedesignationsappearinthis GregWiegand book,andthepublisherwasawareofatrademarkclaim,thedesignationshave SeniorAcquisitionsEditor beenprintedwithinitialcapitallettersorinallcapitals. TrinaMacDonald Theauthorandpublisherhavetakencareinthepreparationofthisbook,but DevelopmentEditor makenoexpressedorimpliedwarrantyofanykindandassumenoresponsibility SonglinQiu forerrorsoromissions.Noliabilityisassumedforincidentalorconsequential damagesinconnectionwithorarisingoutoftheuseoftheinformationor ManagingEditor programscontainedherein. SandraSchroeder Full-ServiceProduction Forinformationaboutbuyingthistitleinbulkquantities,orforspecialsales Manager opportunities(whichmayincludeelectronicversions;customcoverdesigns;and JulieB.Nahil contentparticulartoyourbusiness,traininggoals,marketingfocus,orbranding interests),pleasecontactourcorporatesalesdepartmentat ProjectManager [email protected](800)382-3419. MelissaPanagos Forgovernmentsalesinquiries,[email protected]. CopyEditor StephanieGeels ForquestionsaboutsalesoutsidetheU.S.,[email protected]. Indexer JackLewis VisitusontheWeb:informit.com/aw Proofreader LibraryofCongressNumber:2016961010 MelissaPanagos Copyright©2017PearsonEducation,Inc. TechnicalReviewers ChristianBrunschen Allrightsreserved.PrintedintheUnitedStatesofAmerica.Thispublicationis BJMiller protectedbycopyright,andpermissionmustbeobtainedfromthepublisher ChristianNeuss priortoanyprohibitedreproduction,storageinaretrievalsystem,or DominikWagner transmissioninanyformorbyanymeans,electronic,mechanical,photocopying, EditorialAssistant recording,orlikewise.Forinformationregardingpermissions,requestformsand OliviaBasegio theappropriatecontactswithinthePearsonEducationGlobalRights& PermissionsDepartment,pleasevisitwww.pearsoned.com/permissions/. CoverDesigner ChutiPrasertsith ISBN-13:978-0-321-84284-8 ISBN-10:0-321-84284-7 Compositor LoriHughes 1 17 Contents at a Glance Contents vii AbouttheAuthor xv Introduction xvii 1 CPU:Principles 1 2 CPU:MeasurementandTools 17 3 CPU:PitfallsandTechniques 41 4 CPUExample:XMLParsing 79 5 Memory:Principles 99 6 Memory:MeasurementandTools 119 7 Memory:PitfallsandTechniques 137 8 MemoryExample:FilterStreams 161 9 Swift 173 10 I/O:Principles 205 11 I/O:MeasurementandTools 215 12 I/O:PitfallsandTechniques 225 13 I/O:Examples 267 14 GraphicsandUI:Principles 295 15 GraphicsandUI:MeasurementandTools 309 16 GraphicsandUI:PitfallsandTechniques 325 17 GraphicsandUI:Examples 343 Index 359 This page intentionally left blank Contents AbouttheAuthor xv Introduction xvii 1 CPU:Principles 1 ASimpleExample 2 ThePerilsof(Micro-)Benchmarking 3 MoreIntegerSumming 5 Swift 6 OtherLanguages 7 ThePowerofHybrids 10 Trends 11 CostofOperations 12 ComputationalComplexity 14 Summary 16 2 CPU:MeasurementandTools 17 Command-LineTools 18 top 18 time 19 sample 20 XcodeGauges 22 Instruments 22 SetupandDataGathering 23 ProfilingOptions 25 BasicAnalysis 27 SourceCode 29 DataMiningI:Focus 32 DataMiningII:Pruning 34 InternalMeasurement 35 Testing 37 Dtrace 38 OptimizationBeyondtheCallofDuty 38 Summary 39 viii Contents 3 CPU:PitfallsandTechniques 41 Representation 41 PrimitiveTypes 42 Strings 45 Objects 48 Accessors 48 PublicAccess 52 ObjectCreationandCaching 52 MutabilityandCaching 53 LazyEvaluation 55 CachingCaveats 56 Pitfall:Generic(Intermediate)Representations 58 ArraysandBulkProcessing 59 Dictionaries 61 Messaging 64 IMPCaching 66 Forwarding 69 UniformityandOptimization 71 Methods 71 Pitfall:CoreFoundation 71 Multicore 72 Threads 73 WorkQueues 74 MatureOptimization 75 4 CPUExample:XMLParsing 79 AnHTMLScanner 80 MappingCallbackstoMessages 83 Objects 85 Objects,Cheaply 87 Evaluation 90 Tune-Ups 93 OptimizingtheWholeWidget:MAX 94 MAXImplementation 96 Summary 97