java - 使用 System.arraycopy(...) 比使用 for 循环复制数组更好吗?

标签 java

我想创建一个新的对象数组,将两个较小的数组放在一起。

它们不能为空,但大小可以为 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/

相关文章:

java - 当我的应用程序关闭时,当引用另一个类中的静态方法时,字符串在扩展 BroadcastReceiver 的类中返回 null

java - 如何识别我从black-berry/iphone/ipad收到的电子邮件?

java - 如何向 JPanel 添加多个 JComponent?

java - 需要从启动屏幕重定向到网页

java - 如何获取 JUnit 5 中测试的当前重复次数?

java - 我将如何比较两个将转换为相同字符的字符?

java - Guice 的层次依赖

java.lang.NoSuchMethodException : scala. collection.immutable.$冒号$冒号

java - 当我使用 java 从文件夹下载 Excel 时,出现此错误 "the format and extension of the .xls file do not match. The file may be damaged"

java - Axis 版本 1.4.1 部署在 IBM WAS 8.5 上