-
Struct & ClassProgramming/iOS 2019. 11. 6. 17:54
Struct : value type
Class : reference type
차이점1. struct 는 값이 복사되고, class 는 참조가 된다.
차이점2. struct 가 class 보다 생성이 빠르다.
차이점3. struct 는 상속이 불가능하다.
struct TestStruct { var name: String var age: Int init(name: String, age: Int) { self.age = age self.name = name } } class TestClass { var name: String var age: Int init(name: String, age: Int) { self.age = age self.name = name } }
변수와 초기화 함수를 같은 형태로 정의했을때,
var testStruct: [TestStruct] = [] var testClass: [TestClass] = [] // struct 로 만들때 let startTime = CFAbsoluteTimeGetCurrent() for _ in 0..<1000000 { TestStruct.init(name: "structName", age: 0) } let durationTime = CFAbsoluteTimeGetCurrent() - startTime // class 로 만들때 let startTime2 = CFAbsoluteTimeGetCurrent() for _ in 0..<1000000 { TestClass.init(name: "className", age: 0) } let durationTime2 = CFAbsoluteTimeGetCurrent() - startTime2
Struct durationTime : 0.017071962356567383
class durationTime: 0.1767270565032959
struct 로 모델을 생성하는것이 훨씬 빠르다는 것을 알 수 있다.
참고. 스위프트의 기본 데이터 타입은 struct 로 구현되어 있다.
https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html
Structures and Classes — The Swift Programming Language (Swift 5.1)
Structures and Classes Structures and classes are general-purpose, flexible constructs that become the building blocks of your program’s code. You define properties and methods to add functionality to your structures and classes using the same syntax you u
docs.swift.org
'Programming > iOS' 카테고리의 다른 글
swift] fp - LowHigh (0) 2020.03.05 cocoaPods] 외부 라이브러리 제거후 다시 설치하기 (0) 2020.03.04 swift] fp - fizz buzz 리펙토링 (0) 2020.03.03 swift] fp - 함수형 프로그래밍 기초 (0) 2020.03.03 Timer 만들기 (0) 2019.11.06