$30 off During Our Annual Pro Sale. View Details »

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. async/awaitͷੑೳΛ
    DartͱSwiftͱͷൺֱͰಡΈղ͘
    iOSDC 2021
    Tamappe
    @tamapppe

    View Slide

  2. 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
    גࣜձࣾϨΞδϣϒ

    View Slide

  3. ຊ೔ͷςʔϚ
    async/await
    SwiftͱDartͷൺֱ

    View Slide

  4. ͖͔͚ͬ…
    WWDC 2021Ͱasync/awaitൃද

    View Slide

  5. ͖͔͚ͬ…
    ɾfunctionͰ࢖͑Δ
    ɾError handling Ͱ΋࢖͑Δ
    ɾfor จ(Async sequences)Ͱ΋࢖͑Δͷʁ
    ɾgetterͰ΋࢖͑Δ΍Μʁʁ

    View Slide

  6. ˎasync/await͸ͲͷݴޠͰ΋ૉ੖Β͍͠Ͱ͢
    SwiftͰͷasync/await
    ΊͬͪΌੌ͍΍Μ
    ݁࿦...

    View Slide

  7. Ajenda
    1. async/await ൺֱ
    2. SwiftͰͷasync/await
    3. SwiftͰͷӨڹൣғ
    4. DartͰͷasync/await
    5. DartͰͷϝϦοτɾσϝϦοτ
    6. ·ͱΊ

    View Slide

  8. async/await ൺֱ
    02
    Swift Dart
    Function ○ ○
    Error handling ○ ○
    Property(getter) ○ ×
    Parameter × ○
    Async sequences ○ ×

    View Slide

  9. async/await is …
    03
    1.Simple
    2.Easy
    3.Safe

    View Slide

  10. 04
    SwiftͰͷasync/await

    View Slide

  11. SwiftͰͷasync/await
    05
    Function
    WWDC 2021 Meet async/await in Swift

    View Slide

  12. 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


    }

    View Slide

  13. SwiftͰͷasync/await
    07
    Property (getter)
    WWDC 2021 Meet async/await in Swift

    View Slide

  14. 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)


    }


    }


    }

    View Slide

  15. SwiftͰͷasync/await
    09
    Async sequences (for loop)
    WWDC 2021 Meet async/await in Swift

    View Slide

  16. SwiftͰͷasync/await
    10
    sync to async
    WWDC 2021 Meet async/await in Swift

    View Slide

  17. SwiftͰͷasync/await
    11
    sync to async
    func doSomething() {


    async {


    let data = try await asyncFetchData()


    }


    }

    View Slide

  18. 12
    SwiftͰͷӨڹൣғ

    View Slide

  19. SwiftͰͷӨڹൣғ
    13
    1. ίʔϧόοΫ
    - ίʔϧόοΫ(ωετ)஍ࠈ͔Βͷղ์
    - weakSelf͔Βͷղ์
    2. Thread
    - actorʹΑΓMainActorͰϝΠϯεϨουͰ࣮ߦ
    3. CoreData
    - contextͰͷ΍ΓͱΓ

    View Slide

  20. 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) { }




    }

    View Slide

  21. 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


    // ॲཧΛॻ͘


    })


    })


    })


    }


    }

    View Slide

  22. ίʔϧόοΫ is …
    16
    not Simple
    not Easy
    not Safe

    View Slide

  23. 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


    }




    }

    View Slide

  24. 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)


    // ॲཧΛॻ͘




    }




    }

    View Slide

  25. SwiftͰͷӨڹൣғ (ίʔϧόοΫ)
    19
    1.Simple
    2.Easy
    3.Safe

    View Slide

  26. SwiftͰͷӨڹൣғ (Thread)
    20
    εϨουૢ࡞͸Ͳ͏ͳΔ͔
    - UITableView
    - UICollectionView
    - Viewͷߋ৽ॲཧ

    View Slide

  27. SwiftͰͷӨڹൣғ (Thread)
    21
    class SampleViewController: UIViewController {


    @IBOutlet weak var collectionView: UICollectionView!




    func update() {


    // APIͰσʔλΛऔಘޙʹUIͷߋ৽


    DispatchQueue.main.async {


    self.collectionView.reloadData()


    }


    }


    }

    View Slide

  28. SwiftͰͷӨڹൣғ (Thread)
    22
    ɾactor
    ɾMainActor

    View Slide

  29. 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


    })


    }




    }

    View Slide

  30. SwiftͰͷӨڹൣғ (CoreData)
    24
    synchronous functions (ಉظॲཧ) asynchronous functions (ඇಉظॲཧ)
    .performAndWait await perform
    .perform await perform(.enqueued)

    View Slide

  31. SwiftͰͷӨڹൣғ (CoreData)
    25
    func executePerform() {


    let persistentContainer = NSPersistentContainer(name: "XXX")


    let context = persistentContainer.newBackgroundContext()


    context.perform {


    // ॲཧ


    context.perform {


    // ॲཧ


    context.perform {


    // ॲཧ


    }


    try? context.save()


    }


    }


    }

    View Slide

  32. 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 {


    // ॲཧ


    }


    }

    View Slide

  33. 27
    DartͰͷasync/await

    View Slide

  34. DartͰͷasync/await
    28
    1. ؔ਺ʹasyncΛએݴ͢Δ
    2. ݺͼग़࣌͠ʹawaitΛએݴ
    3. ύϥϝʔλʔ͸Futureܕ
    ˎCombine.frameworkͷFutureͱ͍ۙ

    View Slide

  35. DartͰͷasync/await
    29
    Example: synchronous functions (ಉظॲཧ)
    String createOrderMessage() {
    var order = fetchUserOrder();
    return 'Your order is: $order';
    }
    Future fetchUserOrder() =>
    Future.delayed(const Duration(seconds: 2), () => 'Large Latte',);
    void main() {
    print('Fetching user order...');
    print(createOrderMessage());
    }

    View Slide

  36. DartͰͷasync/await
    30
    Future createOrderMessage() async {
    var order = await fetchUserOrder();
    return 'Your order is: $order';
    }
    Future fetchUserOrder() =>
    Future.delayed(const Duration(seconds: 2), () => 'Large Latte',);
    Future main() async {
    print('Fetching user order...');
    print(await createOrderMessage());
    }
    Example: asynchronous functions (ඇಉظॲཧ)

    View Slide

  37. DartͰͷasync/await
    31
    https://dart.dev/codelabs/async-await

    View Slide

  38. DartͰͷasync/await (then ݺͼग़͠)
    32
    Future hello() async {
    var order = await fetchHello();
    return order;
    }
    Future fetchHello() =>
    Future.delayed(const Duration(seconds: 2), () => 'Hello world',);
    main() async {
    hello()
    .then((value) {
    // thenͰܨ͛Δ
    print(value);
    });
    }

    View Slide

  39. DartͰͷasync/await (Error handling)
    33
    main() async {
    hello()
    .then((value) {
    // thenͰܨ͛Δ
    print(value);
    })
    .catchError((error) {
    // catchError Ͱܨ͛Δ
    print(error);
    });
    }

    View Slide

  40. DartͰͷϝϦοτɾσϝϦοτ
    34
    ϝϦοτ
    ɾDartͷඪ४Ͱasync/await͕࢖͑Δ
    ɾFutureܕ͕͋Δ
    ɾiOS ͷ৚݅ʹറΓ͕ͳ͍

    View Slide

  41. DartͰͷϝϦοτɾσϝϦοτ
    35
    σϝϦοτ
    ɾจ๏͕JavaϥΠΫͰݹ͍ॻ͖ํ
    ɾenum͕SwiftΑΓ΋ॊೈʹॻ͚ͳ͍

    View Slide

  42. 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

    View Slide

  43. 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";
    }
    }
    }

    View Slide

  44. ·ͱΊ
    38
    Swift Dart
    Function ○ ○
    Error handling ○ ○
    Property(getter) ○ ×
    Parameter × ○
    Async sequences ○ ×

    View Slide

  45. Ҿ༻ 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

    View Slide

  46. Ҿ༻ 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/

    View Slide

  47. Thank you!

    View Slide