Using multiple usings, how does this affect performance?

I am not opposed to using the Usage statement, but I wonder how this affects performance when we use it inside one of them.

For example:

        using (test1 (type1))
        {
            using (test2(type2))
            {
                using (test2(type3))
                {
                }
            }
        }

This will be translated into IL as follows:

        try
        {
            try
            {
                try
                {
                }
                finally
                {
                }
            }
            finally
            {
            }
        }
        finally
        { 
        }

This will increase the build size and, in my opinion, affect the performance of the application, right?

Shouldn't we use this?

        type1 test1 = new type1;
        type2 test2 = new type2;
        type3 test3 = new type3;

        try
        {

        }
        finally
        {
          test1.Dispose;
          test2.Dispose;
          test3.Dispose;
        }
+3
source share
4 answers

No, do not use your second form. If you test1.Dispose()throw an exception, for any reason, test2.Dispose()and test3.Dispose()will not be called.

, , . :)

+25

, :

using (test1(type1))
using (test2(type2))
using (test3(type3))
{
    // Code using test1/test2/test3 goes here.
}

try-finally , . ; ( ), ( ), .

+6

, - , !

, . 2() , Dispose test1 , .

+5

//, , , . ( ) , .

, , .

+1

Source: https://habr.com/ru/post/1703171/


All Articles