Friday, 14 November 2008

Java Copying Arrays


There are many ways to copy arrays in Java. I decided to run these benchmarks while writing the buffer pool for a database system I'm writing. The situation (most commonly) arises whenever new pages are brought into the database buffer pool (from disk), their contents need to be copied over the buffer pool, where they are cached. The number of times byte arrays are copied from one place to another is phenomenal, and spread across almost all components of the database, with the buffer manager taking a major portion of these calls.

The code at the end of the post and the benchmark stats below, show us that System.arraycopy is the fastest. The rate at which the time taken increases for the System.arraycopy operation is also a lot lesser than the other methods. I was earlier creating a new object everytime a new database page needed to be cached in memory (yikes!).

performance stats - from 1 to 1 million copy operations -
fill a byte array 1 times.
time taken for for loop fill: 0 ms.
time taken for ac fill: 0 ms.
time taken for clone fill: 0 ms.
time taken for new obj: 0 ms.
fill a byte array 100 times.
time taken for for loop fill: 1 ms.
time taken for ac fill: 1 ms.
time taken for clone fill: 3 ms.
time taken for new obj: 1 ms.
fill a byte array 1000 times.
time taken for for loop fill: 8 ms.
time taken for ac fill: 1 ms.
time taken for clone fill: 5 ms.
time taken for new obj: 2 ms.
fill a byte array 10000 times.
time taken for for loop fill: 99 ms.
time taken for ac fill: 6 ms.
time taken for clone fill: 59 ms.
time taken for new obj: 30 ms.
fill a byte array 100000 times.
time taken for for loop fill: 1085 ms.
time taken for ac fill: 28 ms.
time taken for clone fill: 344 ms.
time taken for new obj: 228 ms.
fill a byte array 1000000 times.
time taken for for loop fill: 11053 ms.
time taken for ac fill: 206 ms.
time taken for clone fill: 2853 ms.
time taken for new obj: 1963 ms.

bug ridden code -