Quantcast
Channel: What is more efficient: System.arraycopy or Arrays.copyOf? - Stack Overflow
Viewing all articles
Browse latest Browse all 11

Answer by aran for What is more efficient: System.arraycopy or Arrays.copyOf?

$
0
0

I posted this on another answer but may be useful here as well.

I know this is not definitive by any means, as benchmarking these kinds of operations is a science on its own, but just for the fun, I made some tests to compare System.arraycopy and Arrays.copyOfRange.

  • Base array is a String[] array, filled with nulls. The size of the array goes from 10 million to 100 million elements.

  • The array is split 24 times.

  • The elapsed time shows the best time from 3 different launches for each base size.

enter image description here

I don't believe there's enough difference in order to conclude that arraycopy is faster in any way. Also, in order to be complete, the test should also include different split sizes (other than 24), as well as other data types and value-filled arrays (other than null).

Test it online(I tested it locally, but may be useful).


Test code

Common block:

 String[] a = new String[baseSize]; // f.e - 10.000.000 int size = baseSize / 24; int rem = baseSize % 24;

And for each method:

System.arraycopy

 long start = System.currentTimeMillis(); String[][]pieces = new String[23][size]; String[] last = new String[size + rem];    for (int i = 0; i < 23; i++)    System.arraycopy(a, (size * i), pieces[i], 0 , size);  System.arraycopy(a, (size * 23), last, 0 ,(size) + rem);  long elapsed = System.currentTimeMillis() - start;

Arrays.copyOfRange

 long start = System.currentTimeMillis(); String[][] pieces = new String[23][]; for (int i = 0; i < 23; i++)    pieces[i] = Arrays.copyOfRange(a, size * i, size * (i + 1));  String[] last = Arrays.copyOfRange(a, size * 23, (size * 24) + rem); long elapsed = System.currentTimeMillis() - start;

The code is easily configurable, so feel free to play with the total pieces to split into, data types, filled arrays and so on. Have fun!


Viewing all articles
Browse latest Browse all 11

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>