简体   繁体   中英

Is it better to cache BinaryFormatter or keep re-creating it?

Is the code below good practice, or is it better to cache BinaryFormatter in a field so it doesn't keep getting re-created?

    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();
            }
        }
    }

when you accessing file system make sure you use using statements to avoid any memory leaks

don't see any problem recreating the formatter object

    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);
        }
        
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM