Thanks!!! The reason didn’t go with Span.copy_from is that the doc states: "Performs an element wise copy from all elements of other into all elements of self. So sounded like a simple for-loop which I thought might be a fair bit slower.
Is this optimized under the hood or is the overhead very low any way?
I’ve been updating my Mojo code to v1.0 and beyond recently. I also just noticed the Span.copy_from function. Love it! It’s been replacing all my previous uses of memcpy.
Is this optimized under the hood or is the overhead very low any way?
And glancing at the std lib source, it looks like copy_from will use a memcpy if the types are simple enough, otherwise a for loop and all the copyinit functions that are necessary.
Did a quick test and indeed hardly any differences (that is with my solution not even doing the required checks yet). So indeed the Span is a very nice (and way more robust) solution.
def arraycopy2[T: Copyable & Deinitable, N: Int, M: Int](src: Array[T, N], src_offset:Int, mut dest: Array[T,M], dest_offset: Int, count:Int):
Span(dest)[
dest_offset: dest_offset+count
].copy_from(
Span(src)[src_offset: src_offset+count]
)
def main() raises:
var buffer1 = Array[Float64, 1000](fill=0.0)
var buffer2 = Array[Float64, 1000](fill=1.1)
var start = perf_counter()
for _ in range(1_000_000):
for i in range(100):
arraycopy2(buffer1, i, buffer2, i+50, 500)
print(perf_counter() - start, buffer2[100])