public void testHardCopyBytes(){ byte[] bytes = new byte[0x5000000]; 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]; byte[] out = new byte[bytes.length]; System.arraycopy(bytes, 0, out, 0, out.length);}我知道JUnit测试并不是最佳的基准测试,但是
testHardCopyBytes完成了0.157s,
而
testArrayCopyBytes 完成了0.086s。
我认为这取决于虚拟机,但看起来好像它复制内存块而不是复制单个数组元素。这将绝对提高性能。
编辑:
看起来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
多么奇特!
谢谢,达伦,指出引用的复制方式有所不同。这使这个问题变得更加有趣!



