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

Introduction to Memory Management in Swift - S...

marcy731
October 26, 2023
17

Introduction to Memory Management in Swift - Swiftのメモリ管理を知る -

2023/10/26
STORES モバイルLT会!- 2023年秋の気配編 -

marcy731

October 26, 2023
Tweet

Transcript

  1. 1. ஋ܕͱࢀরܕ 2. ϝϞϦ഑ஔʢStack / Heapʣ 3. ARC (Automatic Reference

    Counting)ͱࢀরΧ΢ϯτ 4. ॥؀ࢀরͱͦͷରࡦ 5. ڧࢀর / ऑࢀর / ඇॴ༗ࢀর 6. ࠓճૺ۰ͨ͠Stack Over f lowͱͦͷରࡦ ໨࣍
  2. • ஋ܕ • σʔλ͕௚઀ίϐʔ͞ΕΔ • ExɿStruct / Enum / Double(Int)

    / String / Array / Dictionary / Tuple / Set • ϙΠϯτ • Swift͸஋ܕத৺ͷݴޠ • ίϨΫγϣϯܕʢArray, Dictionaryʣ΋ʮcopy-on-writeʯͷ࢓૊ΈͰ஋ܕʹͳ͍ͬͯΔ • ࢀরܕ • σʔλͷ৔ॴ΁ͷࢀর͕ίϐʔ͞ΕΔ • ExɿClass / Function / Clusures ஋ܕͱࢀরܕ
  3. • Memory Layout ϝϞϦ഑ஔʢStack / Heapʣ Code / Global Variable

    Heap Stack Beginning of Memory End of Memory
  4. • StackྖҬ • ओʹ஋ܕͷσʔλ΍Ұ࣌తͳσʔλ͕อଘ • ؔ਺ͷݺͼग़͠΍ϩʔΧϧม਺ͷ֨ೲ • ֨ೲ͞Εͨσʔλ͸ɺͦͷείʔϓ΍ϥΠϑαΠΫϧ͕ऴྃ͢Δͱࣗಈతʹղ์ • HeapྖҬ

    • ࢀরܕͷΠϯελϯε͕อଘ͞ΕΔྖҬ • ϝϞϦͷ֬อ΍ղ์Λ໌ࣔతʹߦ͏ඞཁ͕͋Δ • SwiftͰ͸ARC (Automatic Reference Counting)Λ༻͍ͯࣗಈతʹ؅ཧ ϝϞϦ഑ஔʢStack / Heapʣ
  5. • copy-on-assignment • ஋ܕͷσʔλΛ୅ೖ͢Δͱ͖ɺσʔλ͕࣮ࡍʹίϐʔ͞ΕΔੑ࣭ • Φʔόʔϔουͳ͘ߴ଎ʹΞΫηε • copy-on-write • SwiftͷίϨΫγϣϯ౳Ͱར༻͞ΕΔɺσʔλ͕มߋ͞ΕΔ·ͰίϐʔΛ஗Ԇͤ͞Δ࢓૊Έ

    • ޮ཰తͳϝϞϦ࢖༻Λ࣮ݱ • ྫ͑͹RubyͷArray͸ࢀরܕ͕ͩɺSwiftͷArray͸copy-on-writeͷ࢓૊ΈͰ஋ܕͱͯ͠; Δ·͏ copy-on-assignment / copy-on-write
  6. • ARC (Automatic Reference Counting) • HeapྖҬͷϝϞϦ؅ཧͷ࢓૊Έ • ࢀরܕͷΠϯελϯεͷࢀর਺ΛΧ΢ϯτ͢ΔγεςϜ •

    ͜ͷΧ΢ϯτΛʮࢀরΧ΢ϯτʯͱ͍͏ • ࢀরΧ΢ϯτ • Πϯελϯε΁ͷ৽͍͠ڧ͍ࢀর͕࡞ΒΕΔɹ+1 • ͦͷࢀর͕ͳ͘ͳΔɹ-1 • ࢀরΧ΢ϯτ͕0ʹͳͬͨͱ͖ɺͦͷΠϯελϯε͸ϝϞϦ͔Βղ์ • ARCΛ࢖༻͢Δ͜ͱͰखಈͷϝϞϦղ์ͷඞཁ͕ͳ͘ͳΔ ARCͱࢀরΧ΢ϯτ
  7. • ڧࢀর(Strong) • ΦϒδΣΫτ΁ͷ௨ৗͷࢀর • ࢀরΧ΢ϯτ +1 • ऑࢀর(weak) •

    ΦϒδΣΫτ΁ͷࢀরΛ࣋ͭ΋ͷͷɺࢀরΧ΢ϯτΛ૿΍͞ͳ͍ࢀর • ΦϒδΣΫτ͕ղ์͞ΕΔͱࣗಈతʹnilʹͳΔ • ඇॴ༗ࢀর(unowed) • ऑࢀরͱࣅ͍ͯ·͕͢ɺnilʹͳΔ͜ͱΛڐ༰͠ͳ͍ • ࢀর͍ͯ͠ΔΦϒδΣΫτ͕ղ์͞ΕΔલʹඇॴ༗ࢀরࣗମ͕ղ์͞ΕΔ͜ͱΛอূ͢Δඞཁ͕͋Δ ڧࢀর / ऑࢀর / ඇॴ༗ࢀর
  8. • ݪҼ • TCA͸ReduxΞʔΩςΫνϟ • Ruducer / State ͸StructͰఆٛ͞ΕΔ •

    State͸ࢠStateΛෳ਺࣋ͯΔωετߏ଄ • Structͷωετ͞ΕͨFieldͷංେԽ͸ϥϯλΠϜ࣌ʹStackΛѹഭɺ StackOver f lowʹؕͬͨ • iPhone ͷStackϝϞϦ͸1MB΄Ͳͱখ͍͞ʢSimulator͸8MBʣ • ରࡦ • TCA͸Stackʹ͋ΔσʔλΛHeapʹಀͨ͢ΊʹCoWΛར༻ͨ͠ PresentationStateͱ͍͏࢓૊ΈΛಋೖ͍ͯ͠ΔͷͰɺͦΕΛར༻ • ࢠυϝΠϯͷঢ়ଶΛHeapͰ؅ཧ͢Δ͜ͱͰɺޮ཰త͔ͭ҆શʹঢ়ଶΛ؅ཧ ࠓճૺ۰ͨ͠Stack Over f lowͱͦͷରࡦ
  9. • Swift͸ૉ੖Β͍͠ϝϞϦ؅ཧγεςϜΛ࣋ͭ • ͦͷͨΊɺීஈ͋·ΓϝϞϦ؅ཧΛҙࣝͤͣʹΞϓϦ։ൃ͕Ͱ͖Δ • ஫ҙ఺ • ॥؀ࢀরʹ͸ؾΛ͚ͭΑ͏ • ஋ܕͱࢀরܕͷซ༻࣌ʹ͸ؾΛ͚ͭΑ͏

    • ͜ͷͱ͖ͷ஋ܕ͸StackͰ͸ͳ͘Heapʹ֨ೲ͞ΕύϑΥʔϚϯε͕མͪΔ • StructΛωετ͠State؅ཧΛ͢Δ৔߹ɺStack Over f lowʹؾΛ͚ͭΑ͏ ·ͱΊ