1

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.

Biman Ghosh
  • 113
  • 7

2 Answers2

2

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.

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
1

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.

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • So it could mean that the reason for my code to have a little bit more time complexity is due to the sort()? what sorting algorithm does the sort() use, can you tell ? – Biman Ghosh Apr 07 '13 at 14:23
  • It's possible (profile it first!), but bear in mind that that algorithm is heavily optimized already. Look at this [post](http://stackoverflow.com/questions/4018332/is-java-7-using-tim-sort-for-the-method-arrays-sort) to understand the algorithm being used – Óscar López Apr 07 '13 at 14:25