Java 中是否有与 memcpy() 等效的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3329163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:13:16  来源:igfitidea点击:

Is there an equivalent to memcpy() in Java?

javabytearray

提问by simon

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 Java?

我有一个字节 [],想将它复制到另一个字节 []。也许我在这里展示了我简单的“C”背景,但是在 Java 中的字节数组上是否有与 memcpy() 等效的东西?

采纳答案by Tom

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

您可以尝试System.arraycopy或使用类中的数组函数,Arrays例如java.util.Arrays.copyOf. 两者都应该为您提供引擎盖下的原生性能。

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

Arrays.copyOf 可能有利于可读性,但仅在 java 1.6 中引入。

 byte[] src = {1, 2, 3, 4};
 byte[] dst = Arrays.copyOf(src, src.length);
 System.out.println(Arrays.toString(dst));

回答by Artem Barger

You can use System.arraycopy

您可以使用System.arraycopy

回答by mdma

You can use System.arrayCopy. It copies elements from a source array to a destination array. The Sun implementation uses hand-optimized assembler, so this is fast.

您可以使用System.arrayCopy。它将元素从源数组复制到目标数组。Sun 实现使用手动优化的汇编程序,因此速度很快。

回答by Zaki

Use System.arraycopy()

使用System.arraycopy()

System.arraycopy(sourceArray, 
                 sourceStartIndex,
                 targetArray,
                 targetStartIndex,
                 length);

Example,

例子,

String[] source = { "alpha", "beta", "gamma" };
String[] target = new String[source.length];
System.arraycopy(source, 0, target, 0, source.length);


or use Arrays.copyOf()
Example,


或使用Arrays.copyOf()
示例,

target = Arrays.copyOf(source, length);

java.util.Arrays.copyOf(byte[] source, int length)was added in JDK 1.6.

The copyOf()method uses System.arrayCopy()to make a copy of the array, but is more flexible than clone()since you can make copies of parts of an array.

java.util.Arrays.copyOf(byte[] source, int length)是在 JDK 1.6 中添加的。

copyOf()方法用于System.arrayCopy()制作数组的副本,但比clone()您可以制作数组部分的副本更灵活。

回答by McDowell

If you just want an exact copy of a one-dimensional array, use clone().

如果您只想要一维数组的精确副本,请使用clone().

byte[] array = { 0x0A, 0x01 };
byte[] copy = array.clone();

For other array copy operations, use System.arrayCopy/Arrays.copyOfas Tom suggests.

对于其他数组复制操作,按照Tom 的建议使用System.arrayCopy/ 。Arrays.copyOf

In general, cloneshould be avoided, but this is an exception to the rule.

一般来说,clone应该避免,但这是规则的一个例外。

回答by Peter Schaeffer

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

Java 实际上确实有类似 memcpy() 的东西。Unsafe 类有一个 copyMemory() 方法,它本质上与 memcpy() 相同。当然,和memcpy()一样,它没有提供对内存覆盖、数据破坏等的保护,目前还不清楚它到底是memcpy()还是memmove()。它可用于从实际地址复制到实际地址或从引用复制到引用。请注意,如果使用引用,则必须提供偏移量(否则 JVM 将尽快死亡)。

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.

Unsafe.copyMemory() 有效(在我疲惫不堪的旧电脑上每秒高达 2 GB)。使用风险自负。请注意,并非所有 JVM 实现都存在 Unsafe 类。

回答by Steven Stewart-Gallus

Use byteBufferViewVarHandleor byteArrayViewVarHandle.

使用byteBufferViewVarHandle或 byteArrayViewVarHandle。

This will let you copy an array of "longs" directly to an array of "doubles" and similar with something like:

这将让您将“longs”数组直接复制到“doubles”数组中,类似于:

public long[] toLongs(byte[] buf) {
    int end = buf.length >> 3;
    long[] newArray = new long[end];
    for (int ii = 0; ii < end; ++ii) {
        newArray[ii] = (long)AS_LONGS_VH.get(buf, ALIGN_OFFSET + ii << 3);
    }
}

private static final ALIGN_OFFSET = ByteBuffer.wrap(new byte[0]).alignmentOffset(8); 
private static final VarHandle AS_LONGS_VH = MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.nativeOrder());

This will let you do the bit hacking like:

这将让你做一些黑客攻击:

float thefloat = 0.4;
int floatBits;
_Static_assert(sizeof theFloat == sizeof floatBits, "this bit twiddling hack requires floats to be equal in size to ints");
memcpy(&floatBits, &thefloat, sizeof floatBits);

回答by Steven Stewart-Gallus

No.Java does not have an equivalent to memcpy. Java has an equivalent to memmoveinstead.

。Java 没有与memcpy. Java 有一个等价于memmove

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.

如果 src 和 dest 参数引用同一个数组对象,则执行复制就像将 srcPos 到 srcPos+length-1 位置的分量首先复制到具有长度分量的临时数组,然后将临时数组的内容复制到通过目标数组的 destPos+length-1 复制到位置 destPos。

Oracle Docs

甲骨文文档

It is very likely System.arraycopywill never have the same performance as memcpyif srcand destrefer to the same array. Usually this will be fast enough though.

它很可能System.arraycopy永远不会具有与memcpyifsrcdest引用同一个数组相同的性能。不过通常这会足够快。