我想创建一个新的对象数组,将两个较小的数组放在一起。
它们不能为空,但大小可以为 0。
我无法在这两种方式之间进行选择:它们是等效的还是更有效的一种(例如 system.arraycopy() 复制整个 block )?
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]
}
}
唯一的区别是代码的外观吗?
编辑:感谢链接问题,但他们似乎有一个 Unresolved 讨论:
it is not for native types
真的更快吗? :字节[],对象[],字符[]?在所有其他情况下,将执行类型检查,这将是我的情况,因此将是等效的......不是吗?
在另一个链接的问题上,他们说 the size matters a lot
,对于大小 >24 system.arraycopy() 获胜,对于小于 10,手动 for 循环更好...
现在我真的很困惑。
最佳答案
public void testHardCopyBytes()
{
byte[] bytes = new byte[0x5000000]; /*~83mb buffer*/
byte[] out = new byte[bytes.length];
for(int i = 0; i < out.length; i++)
{
out[i] = bytes[i];
}
}
public void testArrayCopyBytes()
{
byte[] bytes = new byte[0x5000000]; /*~83mb buffer*/
byte[] out = new byte[bytes.length];
System.arraycopy(bytes, 0, out, 0, out.length);
}
我知道 JUnit 测试并不是最好的基准测试,但是
testHardCopyBytes 耗时 0.157 秒完成
和
testArrayCopyBytes 完成耗时 0.086 秒。
我认为这取决于虚拟机,但它看起来好像复制内存块而不是复制单个数组元素。这绝对会提高性能。
编辑:
看起来 System.arraycopy 的表现无处不在。
当使用字符串而不是字节,并且数组很小(大小为 10)时,
我得到了这些结果:
String HC: 60306 ns
String AC: 4812 ns
byte HC: 4490 ns
byte AC: 9945 ns
这是数组大小为 0x1000000 时的样子。看起来 System.arraycopy 肯定会以更大的数组获胜。
Strs HC: 51730575 ns
Strs AC: 24033154 ns
Bytes HC: 28521827 ns
Bytes AC: 5264961 ns
多么奇特!
感谢 Daren 指出引用的复制方式不同。它使这成为一个更有趣的问题!
关于java - 使用 System.arraycopy(...) 比使用 for 循环复制数组更好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18638743/