Embedd_0913
Embedd_0913

Reputation: 16565

Performance issue with following C# code

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 ?

Upvotes: 1

Views: 137

Answers (2)

Polyfun
Polyfun

Reputation: 9639

You should refactor your code so that is impossible to call SaveData with type == 2 if the stream has not been successfully created and _fStream assigned. Thus you will not have to worry about _fStream being null. You will still need a try...catch around SaveDataToFile, because file writes can fail for all sorts of reasons (out of disk space, other locks on the file etc).

Upvotes: 0

Ehsan
Ehsan

Reputation: 32721

if (_fStream != null && _fStream.CanWrite), I have a try/catch already in SaveData method? What are the performance issues with that check ?

As a rule of thumb, you should always try to handle the normal flows of the program. Exception handling should be done only for exceptional situations. And you should note that Exception throwing is a costly operation.

If you compare the performance of check and the cost of throwing the exception than definitely it is better to implement the check.

Though, if it is very rare that _fstream is null or _fstream cannot write than the performance of try catch can be compensated. But still it isn't a good way to program.

Upvotes: 1

Related Questions