Question about arraycopy in Java

Started by
3 comments, last by Zahlman 19 years ago
Maybe this should go in the Java forum, but it's also a performance question, so what the heck. Anyway, the System.arraycopy method takes two arrays of Objects, and is supposed to be faster than manually looping over the entries - presumably due to being implemented in low-level C with pointer arithmetic, or something. Now, what if I want to copy an array of primitives, like integers? The compiler doesn't complain, although an int is not an Object. Is there some implicit conversion going on, and if so, does it slow things down? Or does the underlying C just treat pointers, and is agnostic about whether they're pointers to primitives or Objects? I know that this will make absolutely zero difference to the overall performance of the program, short of copying 100k arrays every update cycle; I'm just curious.
To win one hundred victories in one hundred battles is not the acme of skill. To subdue the enemy without fighting is the acme of skill.
Advertisement
While an int is not an object, an array of ints is, that's why arraycopy can take any array as argument.

Internally, an array is just a continuos length of bytes in memory with some extra information attached to it such as length etc. So, a System.arraycopy is (probably) pretty much equivalent to a memcpy in C, and therefore it won't make a difference speedwise what's inside the array in question.
-LuctusIn the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move - Douglas Adams
Java:
int[] a,b;
a = b;

equivalent C:
int *a,*b;
a = b;

All that is done is a single pointer assignement, nothing is copied.
Trap, System.arrayCopy does not merely switch references, it copies part of one array to another. Javadoc for System.arraycopy
-LuctusIn the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move - Douglas Adams
Quote:
Otherwise, if any of the following is true, an ArrayStoreException is thrown and the destination is not modified:

* The src argument refers to an object that is not an array.
* The dest argument refers to an object that is not an array.


Hmm. Anyone else think it should be a ClassCastException for those two cases instead? :s

This topic is closed to new replies.

Advertisement