갑자기 linq 성능에 대해 궁금해하고 테스트를 실시했습니다.linq이 C에서 느린 이유 #
아래 코드는 내 테스트 코드이며 결과는 꽤 놀랍습니다.
아무에게도 linq 작동 방식 및 TryOut보다 느린 이유는 무엇입니까?
Public class TestObject
{
....
....
//this class contain many members
bool deleted;
....
}
class Program
{
public static ConcurrentDictionary<string, TestObject> testDictionary = new ConcurrentDictionary<string, TestObject>();
static void Main(string[] args)
{
//testDictionary is initialized in ohter code and is likely to have 10000 elements.
RandomTest(0);
RandomTest(1);
Console.ReadKey();
}
static void RandomTest(int k)
{
int count = 10000;
List<string> randomId = new List<string>();
Random rnd = new Random();
for (int i = 0; i < count; i++)
{
int randomNumber = rnd.Next(0, testDictionary.Count());
randomId.Add(testDictionary.ElementAt(randomNumber).key);
}
Stopwatch sw = new Stopwatch();
sw.Start();
if (k == 0)
{
for (int i = 0; i < count; i++)
{
var res = checkid(randomId[i]);
}
}
else if (k == 1)
{
for (int i = 0; i < count; i++)
{
var res = checkid2(randomId[i]);
}
}
sw.Stop();
Console.WriteLine("Elapsed time : " + sw.Elapsed);
}
static bool checkid(string id)
{
TestObject t;
return !testDictionary.TryGetValue(id, out t) ?
false : t.deleted ?
false : true;
}
static bool checkid2(string id)
{
return testDictionary.Any(t => t.key == id && !t.Value.deleted)? true : false;
}
나는이 두 가지 방법을 10000 번 실행하고 checkid 방법
아래, 그것은 대부분 미만 00 걸렸다 같은 결과를 보여줍니다 : 00 : 00.002를.
checkid2 방법의 경우 대부분 00 : 00 : 02.2와 00 : 00 : 02.4 사이였습니다.
이것은 큰 차이가 있습니다.
checkid2 메소드가 키가 Id와 같지 않아도 checkid2 메소드가 삭제 된 변수를 검사하기 때문에 checkID 메소드가 해당 키를 찾았을 때만 삭제 된 변수를 검사하기 때문에 이것이 가능합니까?
linq이 사전의 해시 테이블을 사용하지 않기 때문에. 기본적으로 o (n)보다는 o (n) –