【问题标题】:Is using the completed type name in code is faster than a using directive for the whole namespace在代码中使用完整的类型名称比使用整个命名空间的 using 指令更快
【发布时间】:2012-12-22 18:26:47
【问题描述】:

为了获得最佳网站性能,使用:(例如)

Telerik.Web.UI.RadChart ResultChart = new Telerik.Web.UI.RadChart();

比:

using Telerik.Web.UI;

RadChart ResultChart = new RadChart();

如果我在 ASP.net 页面的许多模块中使用了using 指令,编译器会使用一次吗?

【问题讨论】:

    标签: asp.net .net performance dllimport using-statement


    【解决方案1】:

    没有区别。每次需要使用该类型时,编译后的 IL 都会包含完全限定名称。

    using 语句只会使您的代码文件更短且更易于阅读。

    指令在您的代码中出现的次数也没有区别 - 项目引用它所在的程序集就足够了。

    【讨论】:

    • 即使在 .ASPX 中:<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>?
    • @Ala - 是的。这只是让您能够在标记中使用telerik: 的一种方式。
    【解决方案2】:

    没有区别。

    using 语句使您的代码更短且更具可读性。如果在多个模块中使用它是没有问题的。为这两个版本创建了相同的 IL(中间语言)代码。可以查看这两段代码及其IL代码;

    using System;
    
    namespace Programs
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                string s = "Foo";
            }
        }
    }
    

    .method public hidebysig static void  Main(string[] args) cil managed
    {
      .entrypoint
      // Code size       8 (0x8)
      .maxstack  1
      .locals init ([0] string s)
      IL_0000:  nop
      IL_0001:  ldstr      "Foo"
      IL_0006:  stloc.0
      IL_0007:  ret
    } // end of method Program::Main
    

    namespace Programs
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                System.String s = "Foo";
            }
        }
    }
    

    .method public hidebysig static void  Main(string[] args) cil managed
    {
      .entrypoint
      // Code size       8 (0x8)
      .maxstack  1
      .locals init ([0] string s)
      IL_0000:  nop
      IL_0001:  ldstr      "Foo"
      IL_0006:  stloc.0
      IL_0007:  ret
    } // end of method Program::Main
    

    【讨论】:

    • 像您的许多答案一样,您似乎在解释以前的答案,并没有真正添加太多。怎么会?
    • @Oded 我从不根据以前的答案给出答案。当我看到问题并且如果我知道答案时,我更喜欢添加快速答案(当然不是最好的质量)。之后,我会定期更新它以解释我的完整答案。你是我在 SO 中最喜欢的用户之一,实际上,听到你的这句话,我心碎了。
    • 如果我的结论有误,我深表歉意。我从你那里看到的几个答案看起来像是直接改写了其他答案。
    • 有时人们可以在接近接近的时候互相回答接近的答案。我问了一个question about that issue,ChrisF 写了一个comment,我同意他的看法。但是,嘿,没什么大不了的;)
    猜你喜欢
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    相关资源
    最近更新 更多