测试了一下Java各种创建对象的速度,其中没有使用JDK的序列化方式,而选择了号称速度比JDK序列化快很多的fastjson来实现,代码如下
1.new 对象方式
long s1 = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
Vehicle vehicle1 = new Vehicle();
}
System.out.println("通过new方式创建对象耗时:" + (System.currentTimeMillis() - s1));
2.反射方式
long s1 = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
Vehicle vehicle1 = Vehicle.class.newInstance();
}
System.out.println("通过class方式创建对象耗时:" + (System.currentTimeMillis() - s1));
3.通过对象的克隆方式
long s1 = System.currentTimeMillis();
Vehicle vehicle = new Vehicle();
for (int i = 0; i < 10000000; i++) {
Vehicle vehicle1 = (Vehicle) vehicle.clone();
}
System.out.println("通过clone方式创建对象耗时:" + (System.currentTimeMillis() - s1));
4.通过json序列化方式
long s1 = System.currentTimeMillis();
Vehicle vehicle = new Vehicle();
String json = JSON.toJSONString(vehicle);
for (int i = 0; i < 10000000; i++) {
Vehicle vehicle1 = JSON.parseObject(json, Vehicle.class);
}
System.out.println("通过json方式创建对象耗时:" + (System.currentTimeMillis() - s1));
其中类Vehicle代码
public class Vehicle implements Serializable,Cloneable {
private int id;
private String vinCode;
private int model;
private String terminalCode;
private int tonnageType;
private int ownType;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getVinCode() {
return vinCode;
}
public void setVinCode(String vinCode) {
this.vinCode = vinCode;
}
public int getModel() {
return model;
}
public void setModel(int model) {
this.model = model;
}
public String getTerminalCode() {
return terminalCode;
}
public void setTerminalCode(String terminalCode) {
this.terminalCode = terminalCode;
}
public int getTonnageType() {
return tonnageType;
}
public void setTonnageType(int tonnageType) {
this.tonnageType = tonnageType;
}
public int getOwnType() {
return ownType;
}
public void setOwnType(int ownType) {
this.ownType = ownType;
}
@Override
public String toString() {
return Objects.toStringHelper(this).add("id",id).add("vinCode",vinCode).add("model",model).add("terminalCode",terminalCode).add("tonnageType",tonnageType).add("ownType",ownType).toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Vehicle)) return false;
Vehicle vehicle = (Vehicle) o;
if (!terminalCode.equals(vehicle.terminalCode)) return false;
return true;
}
@Override
public int hashCode() {
return terminalCode.hashCode();
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
测试结果如下(时间单位:毫秒):
通过new方式创建对象耗时:6
通过class方式创建对象耗时:84
通过clone方式创建对象耗时:352
通过json方式创建对象耗时:3310