I am facing challenging memory issues in my own application. I want to tackle a memory leakage problem, so instead of creating too many objects and arrays, I want to reuse the last allocated memory (using a pool of objects and arrays).
In one of my scenarios, I want to shift cells of an allocated array to the right for the specific length. For this, I implement the following simple solution:
private void shiftRight(int length) {
for (int index = size + length - 1; index >= length; index--) {
bytes[index] = bytes[index - length];
}
}
As I google for this problem, I found that I can use System.arraycopy
instead of my simple solution.
System.arraycopy(bytes, 0, bytes, length, size);
But I am worry about the performance of System.arraycopy
. As mentioned in the documentation of this method:
If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.
This method uses a temporary array to copy from src to dest. I think this method causes a new performance issue by creating too many arrays in high transaction systems.
Could you please discuss about these two solutions?
Thanks in advance.