Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How clone has more performance than object creation

I'm trying to understand what's happening underneath the clone() method in java, I would like to know how is better than doing a new call

public class Person implements Cloneable {

    private String firstName;
    private int id;
    private String lastName;

    //constructors, getters and setters

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person p = (Person) super.clone();
        return p;
    }

}

this is my clone code i would like to know what's happening underneath and also what's the difference between a new call because.

this is my client code

    Person p = new Person("John", 1, "Doe");
    Person p2 = null;
    try {
         p2 = (Person) p.clone();
    } catch (CloneNotSupportedException ex) {
        Logger.getLogger(clientPrototype.class.getName()).log(Level.SEVERE, null, ex);
    }
    p2.setFirstName("Jesus");
    System.out.println(p);
    System.out.println(p2);
like image 991
lfernandez93 Avatar asked Feb 25 '15 17:02

lfernandez93


2 Answers

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.

like image 129
Andrii Abramov Avatar answered Oct 16 '22 08:10

Andrii Abramov


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

like image 28
Gren Avatar answered Oct 16 '22 08:10

Gren