我目前正在为游戏开发 UDP 服务器。在此服务器中,使用 aByteArrayInputStream
和 aObjectInputStream
将序列化字节转换为对象。为流创建一个变量并在程序关闭时关闭它们一次是否更有效?
像这样:
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();
}
}