Skip to content

Instantly share code, notes, and snippets.

@karwa
Last active October 19, 2022 17:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karwa/35d33be3924e1372197e5e9f5d61363e to your computer and use it in GitHub Desktop.
Save karwa/35d33be3924e1372197e5e9f5d61363e to your computer and use it in GitHub Desktop.
extension Collection {
public subscript(inplace_slice bounds: Range<Index>) -> Slice<Self> {
get { fatalError() }
_modify {
var slice = Slice(base: self, bounds: bounds)
yield &slice
}
}
}
extension RangeReplaceableCollection where Self: MutableCollection {
public subscript(inplace_native bounds: Range<Self.Index>) -> Self.SubSequence {
get { fatalError() }
_modify {
yield &self[bounds]
}
}
}
import Foundation
enum Operation: String {
case sort = "Append"
case append = "Sort"
case removeAll = "RemoveAll"
}
let op = Operation.removeAll
let iterations = 1000
var randomArrays = [[Int]]()
func reset() {
randomArrays.removeAll()
for _ in 0..<iterations {
var testArray = [Int]()
for _ in 0..<10_000 {
testArray.append(Int.random(in: 0 ... .max))
}
randomArrays.append(testArray)
}
}
reset()
let start_norm = CFAbsoluteTimeGetCurrent()
for i in 0..<iterations {
switch op { // This should get optimised away.
case .sort:
randomArrays[i][0..<5000].sort()
case .append:
randomArrays[i][0..<5000].append(42)
case .removeAll:
randomArrays[i][0..<5000].removeAll()
}
}
let end_norm = CFAbsoluteTimeGetCurrent()
let time_norm = (end_norm - start_norm) / Double(iterations)
reset()
let start_slice = CFAbsoluteTimeGetCurrent()
for i in 0..<iterations {
switch op {
case .sort:
randomArrays[i][inplace_slice: 0..<5000].sort()
case .append:
randomArrays[i][inplace_slice: 0..<5000].append(42)
case .removeAll:
randomArrays[i][inplace_slice: 0..<5000].removeAll()
}
}
let end_slice = CFAbsoluteTimeGetCurrent()
let time_slice = (end_slice - start_slice) / Double(iterations)
reset()
let start_array = CFAbsoluteTimeGetCurrent()
for i in 0..<iterations {
switch op {
case .sort:
randomArrays[i][inplace_native: 0..<5000].sort()
case .append:
randomArrays[i][inplace_native: 0..<5000].append(42)
case .removeAll:
randomArrays[i][inplace_native: 0..<5000].removeAll()
}
}
let end_array = CFAbsoluteTimeGetCurrent()
let time_array = (end_array - start_array) / Double(iterations)
print("""
Test Results (\(op.rawValue)):
Iterations: \(iterations)
Regular subscript: \(time_norm * 1000) ms
modify generic Slice<T>: \(time_slice * 1000) ms
modify native SubSeq: \(time_array * 1000) ms
""")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment