使用倍数"使用",这会如何影响性能?

Bru*_*sta 3 c# clr

我并不反对使用"使用"语句,但我想知道当我们在另一个中使用它时这会如何影响性能.

例如:

        using (test1 (type1))
        {
            using (test2(type2))
            {
                using (test2(type3))
                {
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

这个,将在IL中翻译成这样:

        try
        {
            try
            {
                try
                {
                }
                finally
                {
                }
            }
            finally
            {
            }
        }
        finally
        { 
        }
Run Code Online (Sandbox Code Playgroud)

这会增加组装的大小,我相信会影响应用程序的性能,对吧?

我们不应该使用这个吗?

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

        try
        {

        }
        finally
        {
          test1.Dispose;
          test2.Dispose;
          test3.Dispose;
        }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 25

不,不要使用你的第二张表格.如果test1.Dispose()抛出一个异常,出于某种原因,test2.Dispose()test3.Dispose()不会被调用.

如果有的话,性能差异将是微观的.不要因为微不足道的表现而丢掉正确性:)


Nol*_*rin 6

我想你正在寻找以下内容:

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

它相当于你问题中的第一个try-finally语句,虽然显然更具可读性.真的不要担心这里的表现; 它是良好的设计实践和使用嵌套方法的强大功能(如前面的海报所指出的),另外还有易于理解的代码(多亏了多用语句).


Sea*_*ean 5

我不认为担心程序集的大小是我们通常需要担心的,而代价是编写更复杂的维护代码!

您的示例代码确切地说明了为什么我们需要编译器生成它所执行的代码.如果对new type2()的调用失败,那么将永远不会调用test1上的Dispose方法,这会导致资源泄漏.