我想要创建一个新的对象数组,将两个较小的数组组合在一起。
它们不能为空,但大小可能为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:28:28
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.086s完成。
我认为它依赖于虚拟机,但它看起来像是复制内存块,而不是复制单个数组元素。这绝对会提高业绩。
编辑:
看起来,System.arraycopy的性能无处不在。当使用String而不是字节,并且数组很小(大小为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多奇怪啊!
谢谢你,达伦,你指出引用的复制方式不同。它使这成为一个更有趣的问题!
发布于 2013-09-05 14:19:05
Arrays.copyOf(T[], int)更容易阅读。国际上,它使用System.arraycopy(),这是一个本机调用。
你不能再快了!
发布于 2013-09-05 14:18:45
这取决于虚拟机,但是System.arraycopy应该给您提供最接近本机性能的工具。
我已经为嵌入式系统做了两年的java开发人员(性能是一个非常重要的优先事项),而且在任何地方都可以使用System.arraycopy,我已经在现有代码中使用过它/见过它。当性能成为问题时,它总是优先于循环。但是,如果性能不是一个大问题,我会选择循环。读起来容易多了。
https://stackoverflow.com/questions/18638743
复制相似问题