• Advertisement
Sign in to follow this  

Question about arraycopy in Java

This topic is 4710 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement