1

I want to compare the two following methods :

// We reuse the previously created object copy
public double first(double[] input, double[] copy) {
  copy = Arrays.copyOf(input, input.length);
  Arrays.sort(copy);
  return copy[0];
}

// We create the object copy inside the method
public double second(double[] input) {
  double[] copy = Arrays.copyOf(input, input.length);
  Arrays.sort(copy);
  return copy[1];
}

Will first be faster than second ?

How does the garbage collector behave ?

What is the impact of coding like first on larger projects ?

What happens if calling first(input,null)?

user2682877
  • 520
  • 1
  • 8
  • 19
  • 3
    You're not reusing the object stored in `copy` in `first`. – Sotirios Delimanolis Jul 16 '15 at 16:05
  • In addition to @SotiriosDelimanolis, you are just re-assigning the variable copy. copyOf returns a new array, you are doing this operation in both methods. You are simply disregarding what copy was assigned to in the beginning – Brandon Ling Jul 16 '15 at 16:21

2 Answers2

3

Will first be faster than second?

No.

How does the garbage collector behave?

It will do its job: check if there's an object reference that is not referenced by any object anymore or check if there are two or more object references that only are referenced by themselves, so it will sweep them.

Be careful here. In the first case, you're creating a new object reference and storing it in double[] copy, and this reference will be GCed at the end of the method. Remember that Java is pass by value. So, in both pieces of code, the GC will behave the same: the object reference stored in double[] copy is local to the method, so it's probably that the reference is marked for GC after executing the method.

What is the impact of coding like first on larger projects?

It's primarily opinion based. But I would say the second piece of code is preferable. The first one leads to confusion since you're reassigning the value of a parameter with a new object reference, something that you should avoid despite the size of the project.

What happens if calling first(input,null)?

Run the code and see it by yourself =/

Note: you're not reusing any object reference in those pieces of code.

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • "this reference will be GCed at the end of the method" -- isn't it 'eligble' for gc? i don't think you can guarentee it will GC at this time – Brandon Ling Jul 16 '15 at 16:15
  • Actually, first may even be slightly slower than the second, due to an extra value being pushed on the stack for every call (which may be optimised away after a while of course). – biziclop Jul 16 '15 at 16:34
0

Both methods are creating a new object each time they run. They will remain in memory until GC decides to remove them.

If this is not desired you should consider sorting the input array or having a buffer array as an object attribute that you creates on the constructor.

Rodrigo
  • 400
  • 3
  • 7