I have a method which gets called every 100 ms to save some data to the file. The input to this method is byte array, it's a message and message has a type.
private FileStream _fStream;
public void SaveData(byte[] data)
{
try
{
int type = GetTypeOfData(data);
switch (type)
{
case 0:
// do something
break;
case 2:
SaveDataToFile(data);
break;
case 1:
_fStream = File.Create(fileName);
break;
}
}
catch (Exception ex)
{
// log error
}
}
private void SaveDataToFile(byte[] data)
{
if (_fStream != null && _fStream.CanWrite)
{
_fStream.Write(data, 0, data.Length);
}
}
The question is do I need to check whether file stream is null or not or whether
it can write or not every time if (_fStream != null && _fStream.CanWrite), I have a try/catch already in SaveData method ? What are the performance issues with that check ?
nullhas a negligible performance issue, buttry { } catch { }on the other hand, is quite expensive. If you can avoid atry { } catch { }with ao != null, then do it.