測試了一下Java各類建立對象的速度,其中沒有使用JDK的序列化方式,而選擇了號稱速度比JDK序列化快不少的fastjson來實現,代碼以下java
1.new 對象方式json
long s1 = System.currentTimeMillis(); for (int i = 0; i < 10000000; i++) { Vehicle vehicle1 = new Vehicle(); } System.out.println("經過new方式建立對象耗時:" + (System.currentTimeMillis() - s1));
2.反射方式ide
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序列化方式this
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代碼code
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方式建立對象耗時:6terminal
經過class方式建立對象耗時:84get
經過clone方式建立對象耗時:352hash
經過json方式建立對象耗時:3310