Skip to content

Instantly share code, notes, and snippets.

@romyilano
Last active September 28, 2023 23:16
Show Gist options
  • Save romyilano/84b74c6269b8a2b303eda31bf139df28 to your computer and use it in GitHub Desktop.
Save romyilano/84b74c6269b8a2b303eda31bf139df28 to your computer and use it in GitHub Desktop.
swift memory review
  • arrays and variable-size collections use copy-on-write optimization
  • multiple copies of an array share the same storage
// from documentation
// most cases memory is stored contiguously
// remember! in swift these are structs, copying is treated as such
// it's easy to trip this up if you are tired =D
// integer type with reference seamntics
// Arrays, like all variable-size collections in the standard library, use copy-on-write optimization. Multiple copies of an array share the same storage until you modify one of the copies. When that happens, the array being modified replaces its storage with a uniquely owned copy of itself, which is then modified in place. Optimizations are sometimes applied that can reduce the amount of copying.
class IntegerReference {
var value = 10
}
var firstInts = [IntegerReference(), IntegerReference()]
var secondInts = firstInts
// modifications of an instance are visible to each array
firstInts[0].value = 100
print(secondInts[0].value)
// replacements addictiona nd removoval are still vislbe only in the modified aray
firstInts[0] = IntegerReference()
print(firstInts[0].value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment