Last active
June 20, 2022 03:51
-
-
Save jenox/f93996a296c4715ada629f3204ee7860 to your computer and use it in GitHub Desktop.
Performing mutating operations on slices cause copies that are later written back to the source collection. Thus `array[range].sort()` is less efficient than a hypothetical `array.sort(in: range)`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Box<T> { | |
init(value: T) { | |
self.value = value | |
} | |
var value: T | |
} | |
struct MyArray<T> { | |
private var storage: Box<[T]> = Box(value: []) | |
} | |
extension MyArray: ExpressibleByArrayLiteral, MutableCollection, RandomAccessCollection { | |
init(arrayLiteral elements: T...) { | |
self.storage = Box(value: elements) | |
} | |
var startIndex: Int { | |
return self.storage.value.startIndex | |
} | |
var endIndex: Int { | |
return self.storage.value.endIndex | |
} | |
func index(after i: Int) -> Int { | |
return self.storage.value.index(after: i) | |
} | |
func index(before i: Int) -> Int { | |
return self.storage.value.index(before: i) | |
} | |
func index(_ i: Int, offsetBy distance: Int) -> Int { | |
return self.storage.value.index(i, offsetBy: distance) | |
} | |
func distance(from start: Int, to end: Int) -> Int { | |
return self.storage.value.distance(from: start, to: end) | |
} | |
subscript(position: Int) -> T { | |
get { return self.storage.value[position] } | |
set { | |
if !isKnownUniquelyReferenced(&self.storage) { | |
print("need copy") | |
self.storage = Box(value: self.storage.value) | |
} | |
self.storage.value[position] = newValue | |
} | |
} | |
} | |
var array: MyArray<Int> = [4,1,3,2] | |
array[0..<3].sort() // "need copy" | |
print(array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment