【发布时间】:2019-08-15 17:49:35
【问题描述】:
我目前正在为游戏开发 UDP 服务器。在此服务器中,每个刻度使用ByteArrayInputStream 和ObjectInputStream 将序列化字节转换为对象。为流创建一个变量并在程序关闭时关闭它们一次是否更有效?
像这样:
class Main {
private static ByteArrayInputStream byteIn;
private static ObjectInputStream objectIn;
public static void main(String[] args) {
while(true){
receive();
}
//when program is done call close();
}
public static void receive(){
byteIn = new ByteArrayInputStream();
objectIn = new ObjectInputStream(new BufferedInputStream(byteIn));
//do something
}
public static void close(){
objectIn.close();
byteIn.close();
}
}
还是每次都更有效地创建和关闭新流?
像这样:
class Main {
public static void main(String[] args) {
while(true){
receive();
}
}
public static void receive(){
ByteArrayInputStream byteIn = new ByteArrayInputStream();
ObjectInputStream objectIn = new ObjectInputStream(new BufferedInputStream(byteIn));
//do something
objectIn.close();
byteIn.close();
}
}
【问题讨论】:
-
在这两个示例中,由于无限循环,您将每秒创建数百万个输入流
标签: java inputstream outputstream objectoutputstream bytearrayinputstream