I was trying to implement my own ArrayList
class for educational purposes and when I need to make it grow I need to copy the contents of the old small array into the new bigger one.
Doing this with a for loop
is very inefficient and would require O(n) time
depending on the size of the array to be copied. Luckily Java has the System.arraycopy()
function which I suspect doesn't use a for loop
but copies the entire array at once taking way less time.
However is it possible for myself to do these kind of memory copies or is this so deeply buried that only the java compiler can do this?
P.S there are a lot of functions that I don't know how to implement and seem to work using magic System.out.println()
for example or sockets.
For clarification I just want to know how i can do these kind of omptimized memory managments things myself.
In java.lang.System
, you can see declaration, but no source code:
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
That is because it's a native method, implemented in a library provided by JVM. The implementation can differ between JVMs and its binaries differ between platforms as it needs to be compiled for each.
You can write your own native libraries. To achieve the optimization level you want, you need to be proficient with some lower level language like C or Assembler. With higher languages will probably hit the same barrier as in Java, since you usually don't have direct access to memory in those.
A downside of writing your own native library is that your application will no longer be platform independent, because unlike System
, the compiled library you need for it to run is not included in JVM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With