티스토리 뷰


자바를 사용하다보면 System.arraycopy 를 사용하는 곳을 심심치않게 볼 수 있다. 유틸 클래스던 라이브러리던. 뭐 일을 하면서는 실제로 사용할일은 거의 없는듯 하다. 결국 배열을 복사해주는 놈인데 for문을 직접 이용해서 복사해넣는것과 무엇이 빠를까? 

 

 

1. System.arraycopy vs Array hardcopy

 

역시나 찾아보니 System.arraycopy는 native 코드를 호출해서 사용해서 그런지 훨씬 더 빠른 결과가 나온다고 한다. https://stackoverflow.com/questions/18638743/is-it-better-to-use-system-arraycopy-than-a-for-loop-for-copying-arrays

 

Is it better to use System.arraycopy(...) than a for loop for copying arrays?

I want to create a new array of objects putting together two smaller arrays. They can't be null, but size may be 0. I can't chose between these two ways: are they equivalent or is one more effici...

stackoverflow.com

직접 실험해보진 않았지만 내용만으로도 2배 이상 차이가 난다고 한다. 

 

2. System.arraycopy vs Arrays.copyOf

 

Arrays.copyOf는 System.arraycopy를 래핑한 함수일뿐이다. 동일하다는 뜻이다.

System.arraycopy == Arrays.copyOf

public static int[] copyOf(int[] original, int newLength) {
        int[] copy = new int[newLength];
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

 

왠만하면 배열복사를 for문으로 하지는 말고 System.arraycopy나 Arrays.copyOf를 이용하면 될텐데, copyOf가 간편하며 직관적이라 좋다. 전체 길이를 전부 복사하거나, 복사 대상의 객체를 유지하지 않아도 된다면 copyOf를 사용하자. 

 

복사하는 길이를 명시해야하거나, 객체를 유지해야 한다면 System.arraycopy를 사용해주면 되겠다. 

 

 


댓글
최근에 올라온 글
최근에 달린 댓글