gpt4 book ai didi

Java对象保存

转载 作者:行者123 更新时间:2023-12-02 10:47:21 25 4
gpt4 key购买 nike

我正在尝试保存相当大的类。

注意:

我使用 Java 的 ObjectOutputStream 和 ObjectInputStream 进行保存和加载,其中方法 1 Integer[] 是正在保存的对象,而在方法 2 中正在保存 OutputStream/s 缓冲区 (byte[])。

我最想要的:

  • 运行时快速保存和加载
  • 易于他人理解
  • 在类(class)中添加或删除后易于编辑

对于我来说,保存 java 类型类的最佳方法是什么以下两种:

方法1:(IoStreamSerializaion是一个接口(interface),具有以下两个使用的方法)

public final class Item implements IoStreamSerialization {

private int id;

private int amount;


public Item(int id, int amount) {
super();
this.id = id;
this.amount = amount;
}

@Override
public void loadInputStream(InputStream is) {
id = is.readUnsignedByte();
amount = is.readInt();
}

@Override
public OutputStream saveOutputStream() {
OutputStream os = new OutputStream(2);
os.writeByte(id);
os.writeInt(amount);
return os;
}

}

方法2:(IoBinary是一个接口(interface),具有以下两个使用的方法,其中泛型类型arg是要保存的内容)

public final class Item implements IoBinary<Integer[]> {

private int id;

private int amount;


public Item(int id, int amount) {
super();
this.id = id;
this.amount = amount;
}

@Override
public void loadBinary(Integer[] binary) {
id = binary[0];
amount = binary[1];
}

@Override
public Integer[] saveBinary() {
return new Integer[] { id, amount };
}

}

最佳答案

说到性能:“不要猜测,要测量!”

但是,首先要让它运行。如果速度足够快,就停在那里。如果没有分析并找到瓶颈。

你最想要的是什么:

  1. 代码运行正常(即经过测试)
  2. 易于他人理解
  3. 在类(class)中添加或删除后易于编辑
  4. ...
  5. ...
  6. 运行时快速保存和加载

第 2 点和第 3 点与可维护性相关,比速度更重要。为什么?如果您的代码工作正常并且易于维护和更改,那么一旦发现瓶颈,也可以更轻松地更改它以使其运行得更快。

另一方面,如果您的代码速度很快,但难以理解和更改,那么它很快就会开始腐烂和溃烂。

关于Java对象保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52454156/

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