美文网首页
Value Types and Reference Types

Value Types and Reference Types

作者: 踏云小子 | 来源:发表于2022-11-09 08:42 被阅读0次

    Contents

    A brief introduction

    image.png
    • Value Types: Instance of Structs and enums are passed by Value Types, which has its own unique copy of data
    • Reference Types: Instances of Classes are passed by Reference Types, which can have several owners that share a copy

    An example

    Why did they have this difference

    Allocation

    Method dispatch

    Static dispatch
    • 能够在编译期确定执行方法的方式
    • Value types use static dispatch by default
    Dynamic dispatch
    • 无法在编译期确定,只能在运行时去确定执行方法的分派方式
    • Dynamic Dispatch is supported only by reference types
      [图片上传失败...(image-9834c5-1667954505610)]
    Increasing Performance by Reducing Dynamic Dispatch

    我们知道Static dispatch快于Dynamic dispatch,如何在开发中去尽可能使用Static dispatch

    • inheritance constraints: 使用final关键字去修饰Class,以此生成的Final class,使用Static dispatch
    • access control: private关键字修饰,使得方法或属性只对当前类可见。编译器会对方法进行Static dispatch
    • whole module optimization: 检查继承关系,对某些没有标记final的类通过计算,如果能在编译期确定执行的方法,则使用Static dispatch

    When to use Value Types

    This is especially helpful in multi-threaded environments where a different thread could alter your data.
    Use a value type when you want copies to have an independent state, and the data will be used in code across multiple threads.

    In Swift, Array, String, and Dictionary are all value types.

    Mixed Types

    Q&A

    • Value Types是存储在heap还是stack
    • 什么是Static dispatch和dynamic dispatch
    • 初始化class/struct 能在memory graph看到吗
    • Struct里面嵌套了class, 内存allocation会怎么样
    • value types do not support inheritance?
    • why value types can't store mutable data

    refer

    相关文章

      网友评论

          本文标题:Value Types and Reference Types

          本文链接:https://www.haomeiwen.com/subject/roogtdtx.html