Share
Embed
async/awaitの性能をDartとSwiftとの比較で読み解く
iOSDC 2021 のプレゼン資料
「async/awaitの性能をDartとSwiftとの比較で読み解く」
tamappe
September 19, 2021
Transcript
47 slides
-
I N T R O D U C T I
O N Tamappe ϞόΠϧΞϓϦΤϯδχΞ 2014-20193݄·ͰϑϦʔϥϯεͱͯ͠׆ಈ 20194݄ΑΓϨΞδϣϒʹϞόΠϧΞϓϦΤϯδχΞͱͯ͠ೖࣾ झຯ: ϒϩάͷߋ৽ɺσΟζχʔ८Γ(ίϩφʹΑΓࣗॗ) Qiita: https://qiita.com/tamappe Blog: https://tamappe.com Twitter: https://twitter.com/tamapppe 01 גࣜձࣾϨΞδϣϒ -
Ajenda 1. async/await ൺֱ 2. SwiftͰͷasync/await 3. SwiftͰͷӨڹൣғ 4. DartͰͷasync/await
5. DartͰͷϝϦοτɾσϝϦοτ 6. ·ͱΊ -
async/await ൺֱ 02 Swift Dart Function ◦ ◦ Error handling
◦ ◦ Property(getter) ◦ × Parameter × ◦ Async sequences ◦ × -
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 } -
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) } } } -
SwiftͰͷasync/await 11 sync to async func doSomething() { async {
let data = try await asyncFetchData() } } -
SwiftͰͷӨڹൣғ 13 1. ίʔϧόοΫ - ίʔϧόοΫ(ωετ)ࠈ͔Βͷղ์ - weakSelf͔Βͷղ์ 2. Thread
- actorʹΑΓMainActorͰϝΠϯεϨουͰ࣮ߦ 3. CoreData - contextͰͷΓͱΓ -
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) { } } -
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 // ॲཧΛॻ͘ }) }) }) } } -
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 } } -
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) // ॲཧΛॻ͘ } } -
SwiftͰͷӨڹൣғ (Thread) 21 class SampleViewController: UIViewController { @IBOutlet weak var
collectionView: UICollectionView! func update() { // APIͰσʔλΛऔಘޙʹUIͷߋ৽ DispatchQueue.main.async { self.collectionView.reloadData() } } } -
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 }) } } -
SwiftͰͷӨڹൣғ (CoreData) 24 synchronous functions (ಉظॲཧ) asynchronous functions (ඇಉظॲཧ) .performAndWait
await perform .perform await perform(.enqueued) -
SwiftͰͷӨڹൣғ (CoreData) 25 func executePerform() { let persistentContainer = NSPersistentContainer(name:
"XXX") let context = persistentContainer.newBackgroundContext() context.perform { // ॲཧ context.perform { // ॲཧ context.perform { // ॲཧ } try? context.save() } } } -
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 { // ॲཧ } } -
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()); } -
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 (ඇಉظॲཧ) -
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); }); } -
DartͰͷasync/await (Error handling) 33 main() async { hello() .then((value) {
// thenͰܨ͛Δ print(value); }) .catchError((error) { // catchError Ͱܨ͛Δ print(error); }); } -
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 -
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"; } } } -
·ͱΊ 38 Swift Dart Function ◦ ◦ Error handling ◦
◦ Property(getter) ◦ × Parameter × ◦ Async sequences ◦ × -
Ҿ༻ 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 -
Ҿ༻ 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/