C graphics
C graphics

Reputation: 7458

Is System.arraycopy an efficient way for memory shifting and heap usage?

What I want to do is to shift a large array of bytes to 10 higher indexes. I know I can easily do it this way:

byte [] bArray = new byte [1000000];
System.arraycopy(bArray, 0 , bArray, 10, 900000 );

however, in our specific code we will be doing that every time we call a method, and that method is gonna be called a million times in our code. That makes us worry about memory leak as that is going go put lots of work on JVM to reallocate the heap over and over again in high frequency.

Upvotes: 1

Views: 1936

Answers (1)

Hot Licks
Hot Licks

Reputation: 47739

System.arraycopy is perfectly safe to use -- it will not cause "leaks" or somehow corrupt the array. It's also the most efficient way to move large amounts of data within Java.

And System.arraycopy has nothing at all to do with heap management -- it doesn't allocate any additional storage.

That said, moving large amounts of data is not particularly efficient -- it "dirties" the caches, causing performance to crawl. It's worthwhile to consider a different design.

Upvotes: 6

Related Questions