缓存BinaryFormatter更好还是继续重新创建它更好



下面的代码是好的做法,还是最好将BinaryFormatter缓存在字段中,这样它就不会不断被重新创建?

private void SaveLocalData()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = null;
try
{
fs = File.Create(Constants.LOCAL_BINARY_DATA_PATH);
bf.Serialize(fs, this.localData);
}
catch(System.Exception e)
{
print("error saving: " + e.Message);
}
finally
{
if (fs != null)
{
fs.Close();
}
}
}

访问文件系统时,请确保使用using语句来避免任何内存泄漏

重新创建格式化程序对象没有任何问题

private void SaveLocalData()
{
var bf = new BinaryFormatter();

try
{
using (var fs = File.Create(Constants.LOCAL_BINARY_DATA_PATH))
{
bf.Serialize(fs, this.localData);
}

}
catch (System.Exception e)
{
print("error saving: " + e.Message);
}

}

最新更新