Effective C# 学习笔记(十一)尽量缩减函数体的大小,提高运行效率

由于.NET平台的JIT机制会自动优化代码,其运行原理为逐个函数载入,逐个函数进行执行。所以函数体大小及其中声明的变量的多少直接影响着我们程序的运行效率。

如:

//下面的代码在运行时 对于if ,else中的代码一次只会执行一个,对于JIT来讲,运行这个函数会一次加载函数体中的内容,这样很影响效率 :(

public string BuildMsg(bool takeFirstPath)

{

  StringBuilder msg = new StringBuilder();

  if (takeFirstPath)

  {

  msg.Append("A problem occurred.");

  msg.Append("\nThis is a problem.");

  msg.Append("imagine much more text");

  }

  else

  {

  msg.Append("This path is not so bad.");

  msg.Append("\nIt is only a minor inconvenience.");

  msg.Append("Add more detailed diagnostics here.");

  }

  return msg.ToString();

}

//不如写成这样 :)

public string BuildMsg2(bool takeFirstPath)

{

  if (takeFirstPath)

  {

  return FirstPath();

  }

  else

  {

  return SecondPath();

  }

}

 

另外可以用以下代码声明JIT应对代码的执行行为

[MethodImpl(MethodImplOptions.NoInlining)]

 

.net 运行机制为

  1. 你的代码被 C#编译器解析为 IL中间层代码
  2. IL中间层代码又被JIT 编译器解析为机器码
  3. 操作系统执行机器码

 

而对程序员要求就是要尽量让编译器去做优化,写简单短小的代码,不要累坏我们的编译器呦

原文地址:https://www.cnblogs.com/haokaibo/p/2097717.html