How clone has more performance than object creation

lfernandez93 picture lfernandez93 · Feb 25, 2015 · Viewed 10.6k times · Source

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);

Answer

Gren picture Gren · Feb 25, 2015

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