编译器会尽可能对代码进行优化,我们可以为了提高代码的易读性增加一些局部变量,这并不会导致生成冗余代码并导致执行性能的下降。

C# 的编译器可以对代码进行优化,所以,我们在写代码的时候,可以更多地考虑一下代码的易读性问题。

不考虑几本的对齐和换行美化。看一下局部变量优化问题。

例如,我们有一段如下的代码:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace ConsoleApp1
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. var s = DoSomething();
  13. Console.WriteLine(s);
  14. }
  15. static string DoSomething()
  16. {
  17. var s1 = "Hello, world.";
  18. var s2 = s1.ToUpper();
  19. return s2;
  20. }
  21. }
  22. }

在 DoSomething() 这个方法中,里面定义了两个局部变量:

  • s1
  • s2

在 Main() 方法中,定义了一个局部变量:

  • s

定义 s1 和 s2 是为了提高代码的可读性,它们会导致生成冗余的代码,降低执行效率吗?

我们分别在 Debug 模式下和 Release 模式下进行编译,使用 ILDasm 查看生成的中间代码。

在 Debug 下编译之后,DoSomething() 生成的中间代码如下,可以看到实际上有 3 个局部变量。除了我们自己定义的 s1 和 s2 之外,还有一个生成的 V_2,代码的尺寸为 20。

  1. .method private hidebysig static string DoSomething() cil managed
  2. {
  3. // Code size 20 (0x14)
  4. .maxstack 1
  5. .locals init ([0] string s1,
  6. [1] string s2,
  7. [2] string V_2)
  8. IL_0000: nop
  9. IL_0001: ldstr "Hello, world."
  10. IL_0006: stloc.0
  11. IL_0007: ldloc.0
  12. IL_0008: callvirt instance string [mscorlib]System.String::ToUpper()
  13. IL_000d: stloc.1
  14. IL_000e: ldloc.1
  15. IL_000f: stloc.2
  16. IL_0010: br.s IL_0012
  17. IL_0012: ldloc.2
  18. IL_0013: ret
  19. } // end of method Program::DoSomething

看一下 Main() 方法。

有我们定义的 s 这一个局部变量,代码尺寸为 15 个字节。

  1. .method private hidebysig static void Main(string[] args) cil managed
  2. {
  3. .entrypoint
  4. // Code size 15 (0xf)
  5. .maxstack 1
  6. .locals init ([0] string s)
  7. IL_0000: nop
  8. IL_0001: call string ConsoleApp1.Program::DoSomething()
  9. IL_0006: stloc.0
  10. IL_0007: ldloc.0
  11. IL_0008: call void [mscorlib]System.Console::WriteLine(string)
  12. IL_000d: nop
  13. IL_000e: ret
  14. } // end of method Program::Main

而在 Release 模式下,实际上,DoSomething() 中所有的局部变量都被优化掉了。代码尺寸也只有 11 个字节。

  1. .method private hidebysig static string DoSomething() cil managed
  2. {
  3. // Code size 11 (0xb)
  4. .maxstack 8
  5. IL_0000: ldstr "Hello, world."
  6. IL_0005: callvirt instance string [mscorlib]System.String::ToUpper()
  7. IL_000a: ret
  8. } // end of method Program::DoSomething

还可以看一下 Main() 方法,这个局部变量 s 也被优化掉了。代码尺寸也只有 11 字节了。

  1. .method private hidebysig static void Main(string[] args) cil managed
  2. {
  3. .entrypoint
  4. // Code size 11 (0xb)
  5. .maxstack 8
  6. IL_0000: call string ConsoleApp1.Program::DoSomething()
  7. IL_0005: call void [mscorlib]System.Console::WriteLine(string)
  8. IL_000a: ret
  9. } // end of method Program::Main

编译器会尽可能对代码进行优化,我们可以为了提高代码的易读性增加一些局部变量,这并不会导致生成冗余代码并导致执行性能的下降。

版权声明:本文为haogj原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/haogj/p/13889976.html