日期:2014-05-18  浏览次数:20454 次

这样测试LINQ普通查询的效率对不对?
C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Collections;
using System.Diagnostics;

namespace ConsoleApplication11
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Test> list = new List<Test>();
            Test t;
            for (int i = 0; i < 10000000; i++)
            {
                t = new Test() { MyInt = i, MyString = i.ToString() };
                list.Add(t);
            }


            Debug.WriteLine(DateTime.Now);
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].MyString == "9999999")
                {
                    t = list[i];
                    break;
                }
            }

            Debug.WriteLine(DateTime.Now);

            var item = from temp
                       in list
                       where temp.MyString == "9999999"
                       select temp;
            foreach (var it in item)
            {

            }
            Debug.WriteLine(DateTime.Now);
        }
    }
    public class Test
    {
        public int MyInt { get; set; }
        public string MyString { get; set; }
    }
}





我就是想知道linq快还是直接for快

------解决方案--------------------
你这个例子里毫无疑问是for快,Linq慢得不是一点半点,简直不是一个级别...但你要清楚一点,Linq不是以提升执行效率为目的的,相反它是以牺牲执行效率来提升开发效率和易用性的...