代码改变世界

C#中循环结构的效率问题

  Virus-BeautyCode  阅读(4525)  评论(11编辑  收藏  举报

C#中循环结构的效率问题

引言

顺序、选择、循环是一切程序的三大结构。今天我们就来说一说循环中的一个小问题。

内容

c#的循环结构有四种:

  • for
  • while…do…
  • do…while…
  • foreach

在这四种结构中,都有循环结束的判断。大于某个数字,小于某个数字,或者是其他条件表达式的判断。今天我们就说一下关于数字的判断。

我们的数字可能存放在定义好的一个变量中,也可能从是某个集合的长度,也可能是某个方法返回的信息。这里就讨论一下某个方法的返回信息。

假定存在下面的一个方法,返回值是一个List<int>

1
2
3
4
5
6
7
static List<int> GetIntList()
{
     Console.WriteLine("第 {0} 进入GetIntList方法",Counter);
     Counter++;
     return new List<int>(){
                1,2,3,4,5};
}

需要对这个方法的返回结果进行循环处理,刚开始大多数都会这么写,以for循环为例。

1
2
3
for (int i = 0; i < GetIntList().Count; i++)
{
}

后来知道的多了一些,或者是听到别人说,经过自己的验证。发现这个循环判断条件有问题,每次判断都会重新调用GetIntList方法,造成极大地浪费。就会修改成下面的样子。

1
2
3
4
int len=GetIntList().Count;
for (int i = 0; i < len; i++)
{
}

先定义一个变量,保存集合的长度。

经过验证,while…do、do…while也存在类似的问题,也需要注意。

有时候我们需要做的就是对集合里面的每个元素进行处理,我们会选用foreach这个便利的循环结构,因为他不用考虑下标越界的问题。从上面的验证结果看,就会有人说下面的代码有问题。

1
2
3
foreach (int i in GetIntList())
{
}

到底有没有问题呢?需要验证。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Configuration;
using MongoDB.Driver;
using AutoTest.ServiceLocator;
using System.Reflection;
using AutoTest.Common;
 
namespace AutoTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("------------------------------Begin------------------------------");
 
 
            Console.WriteLine("Foreach循环");
            Counter = 1;
            foreach (int i in GetIntList())
            {
            }
            Console.WriteLine("For循环");
            Counter = 1;
            for (int i = 0; i < GetIntList().Count; i++)
            {
            }
            Console.WriteLine("do...while...循环");
            Counter =1;
            int num=0;
            do
            {
                num++;
            }
            while (num < GetIntList().Count );
            Console.WriteLine("while...do...循环");
            Counter = 1;
            num=0;
            while (num < GetIntList().Count)
            {
                num++;
            };
      
            Console.WriteLine("------------------------------End------------------------------");
            Console.ReadKey();
 
        }
        static int Counter=1;
        static List<int> GetIntList()
        {
            Console.WriteLine("第 {0} 进入GetIntList方法",Counter);
            Counter++;
            return new List<int>(){
                1,2,3,4,5};
        }
    }
 
    
}
其实经过验证,发现,foreach不同于其他三个循环结构,是不会发生重复的GetIntList方法调用的。

结论

1、foreach和其他三个循环结构不太一样。

2、需要用事实说话。

Technorati 标签: 循环,for,foreach,while
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2010-06-08 分页存储过程(五)在MS SQL Server中打造更加准确,且有一点效率提升的的分页结果
2010-06-08 NET 应用架构指导 V2 学习笔记(二十一) 设计业务实体
点击右上角即可分享
微信分享提示