swift - When is my struct too large? -
we're encouraged use struct on class in swift.
this because
- the compiler can lot of optimizations
 - instances created on stack lot more performant 
malloc/freecalls 
the downside struct variables copied each time when returning or assigned function. obviously, can become bottleneck too. 
e.g. imagine 4x4 matrix. 16 float values have copied on every assign/return 1'024 bits on 64 bit system.
one way can avoid using inout when passing variables functions, swifts way of creating pointer. we're discouraged using inout.
so question:
 how should handle large, immutable data structures in swift?
 have worry creating large struct many members?
 if yes, when crossing line?
this accepted answer not entirely answering question had: swift copies structs. trick array/dictionary/string/etc wrappers around classes (which contain actual stored properties). way sizeof(array) size of pointer class (memorylayout<array<string>>.stride == memorylayout<unsaferawpointer>.stride)
if have big struct, might want consider wrapping stored properties in class efficient passing around arguments, , checking isuniquelyreferenced before mutating give cow semantics.
structs have other efficiency benefits: don't need reference-counting , can decomposed optimiser.
in swift, values keep unique copy of data. there several advantages using value-types, ensuring values have independent state. when copy values (the effect of assignment, initialization, , argument passing) program create new copy of value. large values these copies time consuming , hurt performance of program.
https://github.com/apple/swift/blob/master/docs/optimizationtips.rst#the-cost-of-large-swift-values
also section on container types:
keep in mind there trade-off between using large value types , using reference types. in cases, overhead of copying , moving around large value types outweigh cost of removing bridging , retain/release overhead.
Comments
Post a Comment