gpt4 book ai didi

java - 为什么java内置序列化比Gson差?

转载 作者:行者123 更新时间:2023-12-01 06:38:50 25 4
gpt4 key购买 nike

我认为Java内置序列化的性能应该不错。和Gson相比,它不需要做词法分析,应该比Gson快。

但在我的测试中,结果却恰恰相反。看我的代码:

package cleancode;

import com.google.gson.Gson;

import java.io.*;

public class SerializationPerformanceTest {

public static final int MAX_LOOP = 1000000;

public static void main(String[] args) throws Exception {
trySerialization();
tryGson();
}

private static void tryGson() {
long start = System.currentTimeMillis();
Gson gson = new Gson();
for (int i = 0; i < MAX_LOOP; i++) {
String json = gson.toJson(createUser());
gson.fromJson(json, User.class);
}
long end = System.currentTimeMillis();
System.out.println("Gson cost: " + (end - start) + "ms");
}

private static void trySerialization() throws IOException, ClassNotFoundException {
long start = System.currentTimeMillis();
for (int i = 0; i < MAX_LOOP; i++) {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ObjectOutputStream stream = new ObjectOutputStream(byteStream);
stream.writeObject(createUser());
byte[] binary = byteStream.toByteArray();

ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(binary);
ObjectInputStream input = new ObjectInputStream(byteArrayInputStream);
input.readObject();
}
long end = System.currentTimeMillis();
System.out.println("Serialization cost: " + (end - start) + "ms");
}

private static User createUser() {
User user = new User();
user.setAaa(newValue());
user.setBbb(newValue());
user.setCcc(newValue());
user.setDdd(newValue());
user.setEee(newValue());
user.setFff(newValue());
user.setGgg(newValue());
return user;
}

private static String newValue() {
return "" + System.currentTimeMillis();
}
}

User是一个java bean:

class User implements Serializable {
private String aaa;
private String bbb;
private String ccc;
private String ddd;
private String eee;
private String fff;
private String ggg;

String getAaa() {
return aaa;
}

void setAaa(String aaa) {
this.aaa = aaa;
}

String getBbb() {
return bbb;
}

void setBbb(String bbb) {
this.bbb = bbb;
}

String getCcc() {
return ccc;
}

void setCcc(String ccc) {
this.ccc = ccc;
}

String getDdd() {
return ddd;
}

void setDdd(String ddd) {
this.ddd = ddd;
}

String getEee() {
return eee;
}

void setEee(String eee) {
this.eee = eee;
}

String getFff() {
return fff;
}

void setFff(String fff) {
this.fff = fff;
}

String getGgg() {
return ggg;
}

void setGgg(String ggg) {
this.ggg = ggg;
}
}

我电脑上的结果:

Serialization cost: 12339ms
Gson cost: 3971ms

Gson 版本比“序列化”版本快得多。为什么?!

我的测试代码有什么问题吗,或者Java内置序列化实际上很慢?

最佳答案

关于java - 为什么java内置序列化比Gson差?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21347670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com