我想要创建一个新的对象数组,将两个较小的数组组合在一起。
它们不能为空,但大小可能为0。
我无法在这两种方法之间做出选择:它们是等效的还是更有效的(例如,system.arraycopy()副本整块)?
MyObject[] things = new MyObject[publicThings.length+privateThings.length];
System.arraycopy(publicThings, 0, things, 0, publicThings.length);
System.arraycopy(privateThings, 0, things, publicThings.length, privateThings.length);或
MyObject[] things = new MyObject[publicThings.length+privateThings.length];
for (int i = 0; i < things.length; i++) {
if (i<publicThings.length){
things[i] = publicThings[i]
} else {
things[i] = privateThings[i-publicThings.length]
}
}唯一的区别是代码的外观吗?
编辑:感谢链接的问题,但他们似乎有一个尚未解决的讨论:
如果it is not for native types:byte[],Object[],char[],它真的更快吗?在所有其他情况下,都会执行类型检查,这将是我的情况,因此将等效.不是吗?
在另一个链接的问题上,他们说the size matters a lot,对于大小>24 system.arraycopy()获胜,对于小于10,手动循环更好.
现在我真的很困惑。
发布于 2013-09-05 14:27:17
执行像Arrays.copyOf(T[], int)这样的本地方法确实有一些开销,但这并不意味着它不快,因为您正在使用JNI执行它。
最简单的方法是编写一个基准测试。
您可以检查Arrays.copyOf(T[], int)是否比正常的for循环更快。
这里的基准代码:-
public void test(int copySize, int copyCount, int testRep) {
System.out.println("Copy size = " + copySize);
System.out.println("Copy count = " + copyCount);
System.out.println();
for (int i = testRep; i > 0; --i) {
copy(copySize, copyCount);
loop(copySize, copyCount);
}
System.out.println();
}
public void copy(int copySize, int copyCount) {
int[] src = newSrc(copySize + 1);
int[] dst = new int[copySize + 1];
long begin = System.nanoTime();
for (int count = copyCount; count > 0; --count) {
System.arraycopy(src, 1, dst, 0, copySize);
dst[copySize] = src[copySize] + 1;
System.arraycopy(dst, 0, src, 0, copySize);
src[copySize] = dst[copySize];
}
long end = System.nanoTime();
System.out.println("Arraycopy: " + (end - begin) / 1e9 + " s");
}
public void loop(int copySize, int copyCount) {
int[] src = newSrc(copySize + 1);
int[] dst = new int[copySize + 1];
long begin = System.nanoTime();
for (int count = copyCount; count > 0; --count) {
for (int i = copySize - 1; i >= 0; --i) {
dst[i] = src[i + 1];
}
dst[copySize] = src[copySize] + 1;
for (int i = copySize - 1; i >= 0; --i) {
src[i] = dst[i];
}
src[copySize] = dst[copySize];
}
long end = System.nanoTime();
System.out.println("Man. loop: " + (end - begin) / 1e9 + " s");
}
public int[] newSrc(int arraySize) {
int[] src = new int[arraySize];
for (int i = arraySize - 1; i >= 0; --i) {
src[i] = i;
}
return src;
}System.arraycopy() 使用JNI (Java )复制数组(或数组的一部分),因此它非常快,因为您可以确认 这里
https://stackoverflow.com/questions/18638743
复制相似问题