Biman Ghosh
Biman Ghosh

Reputation: 133

Is System.arraycopy() and Array.sort() faster or slower than manual process in Java?

I was using these in my code but I think they are may be not as fast as manual coded procedure. I had searched the and found some articles which say that System.arraycopy() is actually faster than copying an array manually. I am not quite sure whether that is correct or not.

Also, the function Array.sort() is the fast compared to what we write in code?

// I am merging the arrays here into a new integer array called newarray3 
    int[] newarray3= new int[input1.length + input2.length];
    System.arraycopy(input1, 0, newarray3, 0, input1.length);
    System.arraycopy(input2, 0, newarray3, input1.length, input2.length);

    //sorting the array.
    Arrays.sort(newarray3);

input1 and input2 are two arrays which are to be merged and then sorted. I want to know whether coding this way is making my program slower. Or could it be something else. Please help.

Upvotes: 1

Views: 832

Answers (2)

Hot Licks
Hot Licks

Reputation: 47739

System.arraycopy will be faster that what you can do by hand in virtually all circumstances, since it can do "bulk" data moves, vs an element at a time. The main exception would be relatively small arrays, since the initial processing inside arraycopy, selecting which algorithm to use, is non-trivial.

Re sort, there's no single sort algorithm that is optimal in all conditions.

Upvotes: 2

Óscar López
Óscar López

Reputation: 236104

arrayCopy() is a native method, so yes it might be faster than a pure Java implementation coded by hand. On the other hand, sort() is a pure java method, but designed for generic sorting - and the specific algorithm used depends on the data type of the array, take a look at this post to understand the details.

You could make your own sorting implementation that's faster by improving the comparison between objects and specializing the algorithm for a certain data type, in fact this is the approach recommended in the book Java Performance Tuning. Anyway, you won't know for sure until a profiler is used for comparison.

Upvotes: 1

Related Questions