In a current article on the Swift language weblog, Graphing Calculator‘s creator Ron Avitzur recounted how his choice to totally rewrite his app in Swift allowed him to shrink its codebase all the way down to 30% of its unique dimension, bettering maintainability and readability whereas not shedding efficiency.
Graphing Calculator is an app that makes it doable to create operate graphs in two and three dimensions. Initially created in 1985, it was bundled by Apple with the unique PowerPC computer systems, later moved on to stay as an unbiased product obtainable for macOS, Home windows, and iOS. After 35 years of continued growth, one of the best ways ahead, says Avitzur, was a full rewrite, though that is all the time a serious feat, requiring a whole lot of work.
Legacy code embodies a long time of hard-learned classes […]. Whereas a contemporary begin may be aesthetically satisfying, it creates an infinite floor space for bugs. In a typical dot launch, focusing testing on new options is simple. With a whole rewrite, the whole lot is new.
Graphing Calculator used a set of various languages and stacks, together with C++ and Goal C/C++, Lex and YACC, AppKit and UIKit, and OpenGL. All of this morphed right into a coherent Swift codebase utilizing SwiftUI and Metallic over 18 months with a discount of the road depend from 152,000 strains to 29,000.
Much less code means much less to debug, much less to learn and perceive, and that alone makes the port simpler to take care of. Utilizing SwiftUI, view controllers go away solely: an enormous win for declarative programming over crucial.
Among the many main advantages of the rewrite, Avitzur mentions the discount in boilerplate code, which made the logic and the which means of code clearer; using worth sorts in assortment sorts, which made it easier to cause about them; the conciseness introduced by sort inference, enumerations, closures, and Swift concurrency.
The largest problem, then again, was conserving the identical degree of efficiency compared to a codebase which had been extremely optimized for over 30 years.
As Avitzur explains in a Twitter thread, the primary port paid a 10x penalty when it comes to efficiency. He might cut back it all the way down to 2x by disabling all Swift runtime checks and utilizing vDSP for innermost loops. One remaining problem, although, is the cost of automatic reference counting on tree traversal, for the reason that Swift compiler has no approach to specify {that a} given portion of the code won’t change any reference counts.
General, says Avitzur, each Swift and SwiftUI have lived as much as their guarantees and opened up the potential for contribute parts of the code in type of stand-alone Swift Packages for mathematical typesetting, modifying, numeric and symbolic computation, and graphing.