0

I'll give an example in c#.

The following two listings achieve the same thing. Case 2 is definitely better styled than case 1 as the try section isolates the line that throws the exception.

I am very curious to know if the performance is different and, if yes, how does it scale up with the quantity of code included in the try section?

And, finally, why is that?

Case 1:

        try
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
            data = (PlayerData)bf.Deserialize(file);
            file.Close();
        } catch (System.Runtime.Serialization.SerializationException e)
        {
            ...
        }

Case 2:

        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
        try
        {
            data = (PlayerData)bf.Deserialize(file);
        } catch (System.Runtime.Serialization.SerializationException e)
        {

        }
        file.Close();
Steak Overflow
  • 7,041
  • 1
  • 37
  • 59

3 Answers3

1

as @jonathon said, the amount of code have no effect on performance, occurrence of exception have performance impact. but be aware of putting your exception prone code in try block, because if you don't handle exceptions, CLR gets the control of your application which is definitely bad and expensive. because call stack unwinds until find proper catch, which there is no handling block (catch block).

Technovation
  • 397
  • 2
  • 12
  • All this answer says is "if you don't put your code in a try block, nothing will catch its exceptions" which is obvious. Am I missing something? This answer isn't particularly informative. – Jonathon Reinhart Apr 24 '15 at 10:13
0

The amount of code in the try block will have no effect on performance. In fact, the presence of the try block at all will have minimal impact. The expense of exceptions in .NET comes when they are thrown, and the runtime has to perform the stack unwind.

Catch only the set of exceptions you care to handle, from the calls you care about.

In your case 2, you're silencing that exception. Is that what you want to so? If you just want to make sure the file is closed, use a try / finally with no catch statement.

See:

Community
  • 1
  • 1
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
-1

The performance cost of try is very small if no exceptions happened. But in case 2 you always close file and it better solution I think. In case 1 if happened some exception file will be closed too, but latter when garbage collector free your FileStream object.

Defter
  • 214
  • 1
  • 7