I am trying to compare the performance of System::arrayCopy vs Unsafe::copyMemory for Object[]. I assume that Unsafe::copyMemory should be faster since it make less checks. However I can't even make it work! Could you pls help me understand what am I doing wrong in the below snippet? JDK I use is Oracle JDK 1.8.
public static final Unsafe UNSAFE;
static
{
final Unsafe unsafe;
try
{
final PrivilegedExceptionAction<Unsafe> action =
() ->
{
final Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
return (Unsafe)f.get(null);
};
unsafe = AccessController.doPrivileged(action);
}
catch (final Exception ex)
{
throw new RuntimeException(ex);
}
UNSAFE = unsafe;
}
public static void main(final String[] args)
{
final Integer[] a = new Integer[1];
a[0] = 42;
final Integer[] b = new Integer[1];
copyUnsafe(a, 0, b, 0, 1);
assert a[0] == b[0];
}
public static void copyUnsafe(
final Object[] src,
final int srcIndex,
final Object[] dest,
final int destIndex,
final int length)
{
UNSAFE.copyMemory(
src,
Unsafe.ARRAY_OBJECT_BASE_OFFSET + srcIndex * Unsafe.ARRAY_OBJECT_INDEX_SCALE,
dest,
Unsafe.ARRAY_OBJECT_BASE_OFFSET + destIndex * Unsafe.ARRAY_OBJECT_INDEX_SCALE,
length * Unsafe.ARRAY_OBJECT_INDEX_SCALE);
}
When i run this method the following exception is thrown:
Exception in thread "main" java.lang.IllegalArgumentException
at sun.misc.Unsafe.copyMemory(Native Method)
at datastructures.Main.copyUnsafe(Main.java:54)
at datastructures.Main.main(Main.java:43)
Appreciate any help!