GeekBand Swift高级编程第一周作业
2016-05-14 本文已影响42人
Hysoka


第一种情况Point是一个类(Class),Rectangle也是一个类。类具有引用属性,在栈里面只有一个指针,指向堆空间的数据。此方法的模型存储传参代价较小,不需要复制全部数据,节约栈空间。缺点是有可能会有安全隐患,指向堆空间的值被其他指针修改,虽然Swift有了ARC管理机制来管理堆空间的释放,但是循环引用还是会造成内存泄露。


第二种情况Point是一个结构(struct),Rectangle是一个类。Point的值存在栈中,Rectangle需要使用他的值时进行复制操作。Rectangle在栈中只有一个指针,指向堆空间的数值。我认为这是最佳的实现方式,既保证了Rectangle中Point的安全性,有没有占用太多栈资源。


第三种情况Point是一个类,Rectangle是一个结构。Point类会通过传引用(指针)的方式传参给Rectangle,虽然Rectangle是一个结构,但是还是会指向Point类堆空间的数据,这样既浪费了栈空间,也没有安全性。这种实现方式是最不推荐的。


第一种情况Point是一个结构,Rectangle也是一个结构。这样做全部是复制数值传递参数,整个传参的过程消耗会比较多,也很占栈的空间。并且函数结束时栈内容也将全部销毁。