Efficient Array copy

I have been playing around with Mojo a bit and enjoying it.

Now trying a simple RingBuffer type of structure. Part of solution is efficient copying of regions between different Arrays.

Would the following snippet be a good approach (still missing the sanity checks etc):


def arraycopy[T: AnyType, N: Int, M: Int](src: Array[T, N], src_offset:Int, mut dest: Array[T,M], dest_offset: Int, count:Int):
    """
    Copy (part) of source Array into destination Array of same type.
    """

    # @TODO some sanity checks to make it safe.
    # count > 0, src_offset + count <= N, dest_offset + count <= M

    var src_ptr = src.unsafe_ptr().unsafe_offset(src_offset)
    var dest_ptr = dest.unsafe_ptr().unsafe_offset(dest_offset)
    unsafe_memcpy(dest=dest_ptr, src=src_ptr, count=count)

Or is there already something in the std lib that is better suited for this purpose (too much unsafe in the above code ?).

Hi @Peter - the best way to go about this without unnecessary unsafe_ code would be to use Span.copy_from

For example, I would perhaps rewrite this as:

    Span(dest)[
        dest_offset: dest_offset+count
    ].copy_from(
        Span(src)[src_offset: src_offset+count]
    )

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])

On my Mac M1 about 5 seconds using Span.