Jayaram
Jayaram

Reputation: 1725

Is clone method expensive in terms of performance compared with Spring provided BeanUtils.copyProperties?

Please provide more details or alternative approaches for this.

Please note: I am not overriding the clone method, also I will be grateful if anybody could explain if I should override the clone method and what the advantage would be.

Upvotes: 1

Views: 1312

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136152

It is not about performance, clone performance is OK. But you can clone only Cloneable objects, while Spring's BeanUtils.copyProperties can copy properties of any JavaBean object (public no-args constructor and setter / getters for properties). E.g. this works fine copying properties of 2 objects of different classes

class X {
    String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

class Y {
    String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

public class Test1 {

    public static void main(String[] args) throws Exception {
        X x = new X();
        x.setName("test");
        Y y = new Y();
        BeanUtils.copyProperties(x, y);
        System.out.println(y.getName());
    }
}

and prints

test

Upvotes: 2

sp00m
sp00m

Reputation: 48837

Can't you use a copy constructor instead?

public class User {

    private String firstname;
    private String lastname;

    // 0-arg constructor
    public User() {        
    }

    // classic constructor
    public User(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }

    // copy constructor
    public User(User copy) {
        firstname = copy.getFirstname();
        lastname = copy.getLastname();
    }

    // accessors omitted

}

Then, you could use it like this:

User johnDoe = new User("john", "doe");
User copy = new User(johnDoe);

It's a quite common way to do, and the advantage is that you manually decide what properties you copy or not, and how you copy them.

Upvotes: 3

Related Questions