-
Notifications
You must be signed in to change notification settings - Fork 12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Swift Memory Layout 和 Runtime #9
Comments
元类型(
|
Size, Stride, Alignmentstruct Year {
let year: Int // 8
}
struct YearWithMonth {
let year: Int
let month: Int
}
let sizeOfYear = MemoryLayout<Year>.size
let instanceOfYear = Year(year: 1984)
let sizeOfYearInstance = MemoryLayout.size(ofValue: instanceOfYear)
print(sizeOfYear) // 8
print(sizeOfYearInstance) // 8
let sizeOfYearWithMonth = MemoryLayout<YearWithMonth>.size
let instanceOfYearWithMonth = YearWithMonth(year: 1984, month: 10)
let sizeOfYearWithMonthInstance = MemoryLayout.size(ofValue: instanceOfYearWithMonth)
print(sizeOfYearWithMonth) // 16
print(sizeOfYearWithMonthInstance) // 16
//__________________________________________________________________________________
struct Puppy {
let age: Int // 8
let name: String // 16
let isTrained: Bool // 1
}
let sizeOfProperties = MemoryLayout<Int>.size + MemoryLayout<String>.size + MemoryLayout<Bool>.size
print(sizeOfProperties) // returns 25, from 8 + 16 + 1
let sizeOfPuppy = MemoryLayout<Puppy>.size
print(sizeOfPuppy) // returns 25
let strideOfPuppy = MemoryLayout<Puppy>.stride
print(strideOfPuppy) // returns 32
// We’ve preserved the alignment requirements of all the values inside the struct: the second integer is at byte 16, which is a multiple of 8.
// That’s why the struct’s stride can be greater than its size: to add enough padding to fulfill alignment requirements.
let alignmentOfPuppy = MemoryLayout<Puppy>.alignment
print(alignmentOfPuppy) // returns 8
// The stride then becomes the size rounded up to the next multiple of the alignment. In our case:
// the size is 25
// 25 is not a multiple of 8
// the next multiple of 8 after 25 is 32
// therefore, the stride is 32
// Size is the number of bytes to read from the pointer to reach all the data.
// Stride is the number of bytes to advance to reach the next item in the buffer.
// Alignment is the the “evenly divisible by” number that each instance needs to be at. If you’re allocating memory to copy data into, you need to specify the correct alignment (e.g. allocate(byteCount: 100, alignment: 4)).
// https://swiftunboxed.com/images/size-stride-alignment-summary.png 参考 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: