Mastering High Performance with Kotlin Overcome performance difficulties in Kotlin with a range of exciting techniques and solutions Igor Kucherenko BIRMINGHAM - MUMBAI Mastering High Performance with Kotlin Copyright © 2018 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Commissioning Editor: Richa Tripathi Acquisition Editor: Sandeep Mishra Content Development Editor: Zeeyan Pinheiro Technical Editor: Ruvika Rao Copy Editor: Safis Editing Project Coordinator: Vaidehi Sawant Proofreader: Safis Editing Indexer: Tejal Daruwale Soni Graphics: Jason Monteiro Production Coordinator: Shraddha Falebhai First published: June 2018 Production reference: 1120618 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78899-664-8 www.packtpub.com mapt.io Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website. Why subscribe? Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals Improve your learning with Skill Plans built especially for you Get a free eBook or video every month Mapt is fully searchable Copy and paste, print, and bookmark content PacktPub.com Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. Contributors About the author Igor Kucherenko is an Android developer at Techery, a software development company that uses Kotlin as the main language for Android development. Currently, he lives in Ukraine, where he is a speaker in the Kotlin Dnipro Community, which promotes Kotlin and shares knowledge with audiences at meetups. You can find his articles about Kotlin and Android development on Medium and a blog for Yalantis, where he worked previously. I'd like to thank my colleague for sharing knowledge, and Packt Publishing for the opportunity to write this book; Russell Snyder for his help with many details; my wife for her patience while I was writing this book. About the reviewer Ganesh Samarthyam is a co-founder of CodeOps Technologies, a software technology, consultancy, and training company based in Bangalore. He has 16 years of experience in the IT industry, and his latest book, Refactoring for Software Design Smells: Managing Technical Debt by Morgan Kaufmann/Elsevier, has been translated to languages such as Korean and Chinese. Ganesh loves exploring anything and everything about technology in his free time. Packt is searching for authors like you If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea. Table of Contents Preface 1 Chapter 1: Identifying Performance Bottlenecks 6 Reasons for performance issues 6 Memory management 7 Garbage collection 8 Working principles of the garbage collector 8 Impacts of garbage collection 10 Heap fragmentation 10 Finalization 11 Resource leaks 14 Memory leaks 16 String pool 22 Memory model 25 The problem of concurrency and parallelism 26 Java Memory Model (JMM) 27 Synchronization 29 Slow rendering 30 Device refresh rate 30 Frame rate 31 Summary 33 Chapter 2: Identifying Indicators of Performance Issues 34 Benchmarking 35 Microbenchmarks 35 Java Microbenchmark Harness (JMH) 36 Benchmark modes 40 Benchmark time units 42 Benchmark state 43 State scope 44 Fixture methods 44 Levels of fixture methods 46 Writing good benchmarks 46 The pitfalls of loops 46 Dead Code Elimination 48 Using black holes 49 Constant folding 50 Kotlin benchmarks 51 IDEA JMH plugin 53 General performance metrics 54 Types of performance testing 54 Performance testing process 55 Table of Contents Overview of performance testing tools 56 JMeter 56 Fabric 58 Summary 59 Chapter 3: Learning How to Use Profiling Tools 60 Memory profiling 60 Memory Viewer 61 HProf 63 Eclipse Memory Analyzer Tool 65 Histogram 68 Shallow and Retained Heap 69 Dominator Tree 71 Top Consumers 71 Analyzing class loaders 73 Android Studio Memory Profiler 74 Memory categories 76 Recording memory allocation 76 Threads profiling 80 Threads viewer 80 Frames pane 81 The Threads pane 83 Thread profiling in the MAT 84 Threads Overview 84 Thread Details 85 CPU Profiler in Android Studio 85 Call Chart and Flame Chart tabs 87 Top Down and Bottom Up tabs 88 Summary 88 Chapter 4: Functional Approach 89 Functional programming 89 Declarative versus imperative 91 Pure functions 92 First-class functions 93 Higher-order functions 96 Function composition 99 Lambdas 101 Closures 102 Typeclasses 103 Arrow library 103 Functor 104 Monad 107 Immutability 115 Inspecting functional features 116 Inline versus non-inline 116 Capturing and non-capturing lambdas 121 [ ii ] Table of Contents Summary 124 Chapter 5: Enhancing the Performance of Collections 125 Data structures 125 Arrays 126 Linked lists 126 Stacks 127 Queues 130 Sets 130 Maps 131 Hash tables 132 Binary search trees 132 Tries 133 Binary heaps 134 Graphs 135 Time complexity 135 Calculating time complexity 136 Time complexity of lists 137 Time complexity of sets 137 Time complexity of queues 138 Time complexity of maps 138 Collections in Kotlin 139 Sequences in Kotlin 143 Summary 146 Chapter 6: Optimizing Access to Properties 147 Fields and properties 147 Backing fields 150 Backing properties 154 @JvmField annotation 157 Compile-time constants 163 Inner classes 166 lateinit 169 Companion objects 173 Summary 177 Chapter 7: Preventing Unnecessary Overhead Using Delegates 178 Types of delegation 179 Explicit delegation 179 Implicit delegation 183 Class delegation 183 Delegated properties 190 Lazy 190 Creating a delegated property 196 Inspecting the lazy function 203 Observable delegates 205 [ iii ] Table of Contents Summary 207 Chapter 8: Ranges and Identifying Performance Issues 208 Ranges in Kotlin 208 Utility functions 221 Range benchmarking 224 Summary 231 Chapter 9: Multithreading and Reactive Programming 232 Concurrency and parallelism 232 Reactive programming 238 Coroutines 250 Setting up a project 251 The launch function 251 The async function 254 The buildSequence function 256 The suspendingSequence function 257 The produce function 259 Coroutines with reactive programming 259 Summary 260 Chapter 10: Best Practices 261 The disposable pattern 261 Immutability 263 Data classes 263 The String pool 266 StringBuilder 267 Functional programming 268 Declarative versus imperative 269 Pure functions 269 First-class functions 269 Higher-order functions 270 Inline functions 271 Function composition 272 Capturing lambdas 274 Collections 275 Properties 275 Backing properties 276 @JvmField annotation 277 Top-level members 278 Compile-time constants 279 The lateinit modifier 280 Delegation 281 Singleton delegate object 281 The lazy funcation with unsafe thread mode 282 [ iv ]