Is there an equivalent to memcpy() in Java?

前端 未结 9 1751
灰色年华
灰色年华 2020-12-25 09:34

I have a byte[] and would like to copy it into another byte[]. Maybe I am showing my simple \'C\' background here, but is there an equivalent to memcpy() on byte arrays in

相关标签:
9条回答
  • 2020-12-25 10:03

    You might try System.arraycopy or make use of array functions in the Arrays class like java.util.Arrays.copyOf. Both should give you native performance under the hood.

    Arrays.copyOf is probably favourable for readability, but was only introduced in java 1.6.

     byte[] src = {1, 2, 3, 4};
     byte[] dst = Arrays.copyOf(src, src.length);
     System.out.println(Arrays.toString(dst));
    
    0 讨论(0)
  • 2020-12-25 10:06

    No. Java does not have an equivalent to memcpy. Java has an equivalent to memmove instead.

    If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.

    Oracle Docs

    It is very likely System.arraycopy will never have the same performance as memcpy if src and dest refer to the same array. Usually this will be fast enough though.

    0 讨论(0)
  • 2020-12-25 10:09

    Java actually does have something just like memcpy(). The Unsafe class has a copyMemory() method that is essentially identical to memcpy(). Of course, like memcpy(), it provides no protection from memory overlays, data destruction, etc. It is not clear if it is really a memcpy() or a memmove(). It can be used to copy from actual addresses to actual addresses or from references to references. Note that if references are used, you must provide an offset (or the JVM will die ASAP).

    Unsafe.copyMemory() works (up to 2 GB per second on my old tired PC). Use at your own risk. Note that the Unsafe class does not exist for all JVM implementations.

    0 讨论(0)
提交回复
热议问题