为此,您可以使用replaceSubrange()
:
let source: [UInt8] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
var dest: [UInt8] = [0, 0, 0, 0, 0, 0, 0, 0, 0]
dest.replaceSubrange(2..<(2+5), with: source[2..<(2+5)])
print(dest) // [0, 0, 3, 4, 5, 6, 7, 0, 0]
或者只需将源片分配给目标片:
dest[2..<(2+5)] = source[2..<(2+5)]
print(dest) // [0, 0, 3, 4, 5, 6, 7, 0, 0]
基准
在MacBook Air M2上,代码在发布配置中编译.
import Foundation
let N = 1_000_000 // Length of source and destination array
let sourceStart = 500
let destinationStart = 2000
let length = 12345
let source: [UInt8] = Array(repeating: 5, count: N)
for _ in 1...10 {
do {
var dest: [UInt8] = Array(repeating: 0, count: N)
let start = Date()
dest[destinationStart..<(destinationStart+length)].withUnsafeMutableBufferPointer { p in
source.copyBytes(to: p, from: sourceStart..<sourceStart + length)
}
let end = Date()
print("copyBytes: ", end.timeIntervalSince(start) * 1000, "ms")
}
do {
var dest: [UInt8] = Array(repeating: 0, count: N)
let start = Date()
source.withUnsafeBytes { sourcePtr in
_ = memcpy(&dest[destinationStart], sourcePtr.baseAddress! + sourceStart, length)
}
let end = Date()
print("memcpy: ", end.timeIntervalSince(start) * 1000, "ms")
}
do {
var dest: [UInt8] = Array(repeating: 0, count: N)
let start = Date()
dest.replaceSubrange(destinationStart..<(destinationStart+length),
with: source[sourceStart..<(sourceStart+length)])
let end = Date()
print("replaceSubrange:", end.timeIntervalSince(start) * 1000, "ms")
}
do {
var dest: [UInt8] = Array(repeating: 0, count: N)
let start = Date()
dest[destinationStart..<(destinationStart+length)]
= source[sourceStart..<(sourceStart+length)]
let end = Date()
print("slicing: ", end.timeIntervalSince(start) * 1000, "ms")
}
print()
}
结果:
copyBytes: 0.010013580322265625 ms
memcpy: 0.0010728836059570312 ms
replaceSubrange: 0.009059906005859375 ms
slicing: 0.010013580322265625 ms