Compare java implementation of deep copy and efficiency in two ways


java achieve deep copy of two ways, writing inaccuracies also please correct me great God

1. Serializing way deep copy;

2. cloned sequentially embodiment each variable domain realization reference type;

code show as below:

Teacher first constructed class that implements the interface, clone method implemented using the sequence of:

class Teacher implements Cloneable,Serializable{
/**

*/
private static final long serialVersionUID = 4390576177500173601L;
public String name;
public String phone;
public Teacher(String name, String phone) {
this.name = name;
this.phone = phone;
}
@Override
protected Object clone() {
Teacher t = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream b= null;
try {
b = new ObjectOutputStream(baos);
b.writeObject(this);

} catch (IOException e) {
e.printStackTrace ();
}finally{
try {
b.close();
} catch (IOException e) {
e.printStackTrace ();
}
}
ByteArrayInputStream bi = new ByteArrayInputStream(baos.toByteArray());
try {
ObjectInputStream oi = new ObjectInputStream(bi);
t = (Teacher) oi.readObject();
oi.close();
bi.close();
} catch (IOException e) {
e.printStackTrace ();
} catch (ClassNotFoundException e) {
e.printStackTrace ();
}

return t;
}

}


Construction Worker class, implemented method of cloning reference

class Worker implements Cloneable{
public String name;
public String phone;
public Worker(String name, String phone) {
this.name = name;
this.phone = phone;
}
@Override
protected Worker clone(){
Worker worker = null;
try {
worker = (Worker) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace ();
}
return worker;
}

}
}


Write Test:

public class CloneCompare {
public static void main(String[] args) {
Worker w = new Worker("lisi", "123");
Teacher t = new Teacher("wangwu", "123123");
long time1 =  System.currentTimeMillis();
for(int a=0;a<10000;a++){
w.clone();
}
System.out.println(System.currentTimeMillis()-time1);
long time2 = System.currentTimeMillis();
for(int a=0;a<10000;a++){
t.clone();
}
System.out.println(System.currentTimeMillis()-time2);
}


}

Test results are as follows:

3
615

Efficiency difference is already 200 times, in fact, the internal class type of application is not a lot of cases, a simple clone of the lead is the best choice.


Published 20 original articles · won praise 0 · views 10000 +

Guess you like

Origin blog.csdn.net/u011248560/article/details/43097847