Upgrade to Pro — share decks privately, control downloads, hide ads and more …

async/awaitの性能をDartとSwiftとの比較で読み解く

tamappe
September 19, 2021

 async/awaitの性能をDartとSwiftとの比較で読み解く

iOSDC 2021 のプレゼン資料
「async/awaitの性能をDartとSwiftとの比較で読み解く」

tamappe

September 19, 2021
Tweet

More Decks by tamappe

Other Decks in Programming

Transcript

  1. I N T R O D U C T I

    O N Tamappe ϞόΠϧΞϓϦΤϯδχΞ 2014೥-2019೥3݄·ͰϑϦʔϥϯεͱͯ͠׆ಈ 2019೥4݄ΑΓϨΞδϣϒʹϞόΠϧΞϓϦΤϯδχΞͱͯ͠ೖࣾ झຯ: ϒϩάͷߋ৽ɺσΟζχʔ८Γ(ίϩφʹΑΓࣗॗ) Qiita: https://qiita.com/tamappe Blog: https://tamappe.com Twitter: https://twitter.com/tamapppe 01 גࣜձࣾϨΞδϣϒ
  2. async/await ൺֱ 02 Swift Dart Function ◦ ◦ Error handling

    ◦ ◦ Property(getter) ◦ × Parameter × ◦ Async sequences ◦ ×
  3. SwiftͰͷasync/await 06 Function func asyncFetchData() async throws -> Data {

    let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")! let request = URLRequest(url: url) let (data, response) = try await URLSession.shared.data(for: request, delegate: nil) guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw NSError(domain: "error", code: -1, userInfo: nil) } return data }
  4. SwiftͰͷasync/await 08 Property (getter) extension UIImage { var thumbnail: UIImage?

    { get async { let size = CGSize(width: 40, height: 40) return await self.byPreparingThumbnail(ofSize: size) } } }
  5. SwiftͰͷasync/await 11 sync to async func doSomething() { async {

    let data = try await asyncFetchData() } }
  6. SwiftͰͷӨڹൣғ 13 1. ίʔϧόοΫ - ίʔϧόοΫ(ωετ)஍ࠈ͔Βͷղ์ - weakSelf͔Βͷղ์ 2. Thread

    - actorʹΑΓMainActorͰϝΠϯεϨουͰ࣮ߦ 3. CoreData - contextͰͷ΍ΓͱΓ
  7. SwiftͰͷӨڹൣғ (ίʔϧόοΫ) 14 class SampleRequest: NSObject { func fetchSomethingA(id: Int,

    compeltion: (Int) -> Void) { } func fetchSomethingB(id: Int, compeltion: (Int) -> Void) { } func fetchSomethingC(id: Int, compeltion: (Int) -> Void) { } }
  8. SwiftͰͷӨڹൣғ (ίʔϧόοΫ) 15 class SampleRequest: NSObject { // தུ func

    requestSomething() { fetchSomethingA(id: 1, compeltion: { [weak self] a in // ॲཧΛॻ͘ self?.fetchSomethingB(id: a, compeltion: { [weak self] b in // ॲཧΛॻ͘ self?.fetchSomethingC(id: b, compeltion: { c in // ॲཧΛॻ͘ }) }) }) } }
  9. SwiftͰͷӨڹൣғ (ίʔϧόοΫ) 17 class SampleRequest: NSObject { func fetchSomethingA(id: Int)

    async -> Int { return 1 } func fetchSomethingB(id: Int) async -> Int { return 2 } func fetchSomethingC(id: Int) async -> Int { return 3 } }
  10. SwiftͰͷӨڹൣғ (ίʔϧόοΫ) 18 class SampleRequest: NSObject { // தུ func

    requestSomething() async { let a = await fetchSomethingA(id: 1) let b = await fetchSomethingB(id: a) let c = await fetchSomethingC(id: b) // ॲཧΛॻ͘ } }
  11. SwiftͰͷӨڹൣғ (Thread) 21 class SampleViewController: UIViewController { @IBOutlet weak var

    collectionView: UICollectionView! func update() { // APIͰσʔλΛऔಘޙʹUIͷߋ৽ DispatchQueue.main.async { self.collectionView.reloadData() } } }
  12. SwiftͰͷӨڹൣғ (Thread) 23 class SampleRequest: NSObject { var number: Int

    = 0 // தུ func requestSomething() async { let a = await fetchSomethingA(id: 1) let b = await fetchSomethingB(id: a) let c = await fetchSomethingC(id: b) // ॲཧΛॻ͘ Task.detached(priority: nil, operation: { @MainActor in // @MainActor ͰϝΠϯεϨουͰߋ৽Ͱ͖Δʁ self.number = c }) } }
  13. SwiftͰͷӨڹൣғ (CoreData) 25 func executePerform() { let persistentContainer = NSPersistentContainer(name:

    "XXX") let context = persistentContainer.newBackgroundContext() context.perform { // ॲཧ context.perform { // ॲཧ context.perform { // ॲཧ } try? context.save() } } }
  14. SwiftͰͷӨڹൣғ (CoreData) 26 func asyncExecutePerform() async { let persistentContainer =

    NSPersistentContainer(name: "XXX") let context = persistentContainer.newBackgroundContext() await context.perform { // ॲཧ } await context.perform { // ॲཧ try? context.save() } await context.perform { // ॲཧ } }
  15. DartͰͷasync/await 29 Example: synchronous functions (ಉظॲཧ) String createOrderMessage() { var

    order = fetchUserOrder(); return 'Your order is: $order'; } Future<String> fetchUserOrder() => Future.delayed(const Duration(seconds: 2), () => 'Large Latte',); void main() { print('Fetching user order...'); print(createOrderMessage()); }
  16. DartͰͷasync/await 30 Future<String> createOrderMessage() async { var order = await

    fetchUserOrder(); return 'Your order is: $order'; } Future<String> fetchUserOrder() => Future.delayed(const Duration(seconds: 2), () => 'Large Latte',); Future<void> main() async { print('Fetching user order...'); print(await createOrderMessage()); } Example: asynchronous functions (ඇಉظॲཧ)
  17. DartͰͷasync/await (then ݺͼग़͠) 32 Future<String> hello() async { var order

    = await fetchHello(); return order; } Future<String> fetchHello() => Future.delayed(const Duration(seconds: 2), () => 'Hello world',); main() async { hello() .then((value) { // thenͰܨ͛Δ print(value); }); }
  18. DartͰͷasync/await (Error handling) 33 main() async { hello() .then((value) {

    // thenͰܨ͛Δ print(value); }) .catchError((error) { // catchError Ͱܨ͛Δ print(error); }); }
  19. Dartͷenum (͓·͚) 36 Swift Dart Normal (Int Value) ◦ ◦

    Iterating over Enumeration Cases ◦ × Associated Values ◦ × Implicitly Assigned Raw Values ◦ × Recursive Enumerations ◦ × https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html
  20. Dartͷenum (͓·͚) 37 // Value͸ int enum Type { First,

    Second, Third, Fourth } // Dartͷ֦ுؔ਺͸ on ͱϥϕϦϯά͕ඞཁ extension TypeExtension on Type { String parseString() { switch (this) { case Type.First: return "First"; case Type.Second: return "Second"; case Type.Third: return "Third"; case Type.Fourth: return "Fourth"; } } }
  21. ·ͱΊ 38 Swift Dart Function ◦ ◦ Error handling ◦

    ◦ Property(getter) ◦ × Parameter × ◦ Async sequences ◦ ×
  22. Ҿ༻ 1 Asynchronous programming https://dart.dev/codelabs/async-await Futures and error handling https://dart.dev/guides/libraries/futures-error-handling

    WWDC 2021 Meet async/await in Swift https://developer.apple.com/videos/play/wwdc2021/10132 WWDC 2021 Meet AsyncSequence https://developer.apple.com/videos/play/wwdc2021/10058 WWDC 2021 Use async/await with URLSession https://developer.apple.com/videos/play/wwdc2021/10095 WWDC 2021 Bring CoreData concurrency to Swift and SwiftUI https://developer.apple.com/videos/play/wwdc2021/10017
  23. Ҿ༻ 2 Async/Await and the Future of Combine https://benscheirman.com/2021/06/async-await-and-the-future-of-combine/ URLsessionΛ༻͍ͨHTTPϦΫΤετͷํ๏(Swift,

    Xcode) https://qiita.com/shungo_m/items/64564fd822a7558ac7b1 Core DataΛόοΫάϥ΢ϯυͰ࢖͏ https://www.2nd-walker.com/2020/10/09/swift-using-coredata-in-background/ {JSON} Placeholder https://jsonplaceholder.typicode.com/