How clone has more performance than object creation
I have created simple benchmark for class Person
:
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
And got the following results:
Benchmark Mode Cnt Score Error Units
MyBenchmark.viaClone avgt 10 10.041 ± 0.059 ns/op
MyBenchmark.viaNew avgt 10 7.617 ± 0.113 ns/op
This simple benchmark demonstrates that instantiating new object and setting corresponding properties from source object takes 25% less time than cloning it.
Joachim is right. If you need copy use Clone, If you need a seprate object (for a seprate person) you should use new
and create a new Object instead.
'More Performance' is subjective and may not be the right term here. What happens in clone is the underlying objects are shared, i.e. they have 2 seprate references to the same memory location. So effectively you save up creating objects and memory. Remember Deep copy / Shallow Copy?
If you need a copy, call clone(), if not, call a constructor.
The standard clone method (java.lang.Object.clone()) creates a shallow copy of the object without calling a constructor. If you need a deep copy, you have to override the clone method.
And don't worry about performance.
Performance depends on the contents of the clone method and the constructors and not from the used technique(new or clone) itself.
Edit: Clone and constructor are not really alternatively to each other, they fullfill different purposes
public void testPerformance(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
long start = System.currentTimeMillis();
for(int i = 0; i < 1000000; i++){
SimpleDateFormat localSdf = (SimpleDateFormat)sdf.clone();
}
System.out.println("Cloning : " + (System.currentTimeMillis() - start) + " ms");
start = System.currentTimeMillis();
for(int i = 0; i < 1000000; i++){
Object localSdf = new SimpleDateFormat("yyyy-MM-dd");
}
System.out.println("Creating : " + (System.currentTimeMillis() - start) + " ms");
}
Cloning : 302 ms Creating : 885 ms