여기에 따라 시작 시간이 달라진다는 것을 알았습니다. 초기화 코드를 배치했습니다. 나는 이것이 정말로 이상하다고 생각 했으므로 나는 작은 기준을 적어 내 의혹을 확인했다. main 메소드가 호출되기 전에 실행되는 코드는 정상보다 느린 것 같습니다.정적 생성자의 코드가 느리게 실행 됨
Benchmark();
이 일반 코드 경로 전후에 호출되는지에 따라 다른 속도로 실행되는 이유는 무엇입니까?
// static Program program = new Program()
public constructor:
894 ms
895 ms
887 ms
884 ms
883 ms
static constructor:
880 ms
872 ms
876 ms
876 ms
872 ms
main method:
426 ms
428 ms
426 ms
426 ms
426 ms
// new Program() in Main()
public constructor:
426 ms
427 ms
426 ms
426 ms
426 ms
반복의 수를 두배로 :
class Program {
static Stopwatch stopwatch = new Stopwatch();
static Program program = new Program();
static void Main() {
Console.WriteLine("main method:");
Benchmark();
Console.WriteLine();
new Program();
}
static Program() {
Console.WriteLine("static constructor:");
Benchmark();
Console.WriteLine();
}
public Program() {
Console.WriteLine("public constructor:");
Benchmark();
Console.WriteLine();
}
static void Benchmark() {
for (int t = 0; t < 5; t++) {
stopwatch.Reset();
stopwatch.Start();
for (int i = 0; i < 1000000; i++)
IsPrime(2 * i + 1);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds + " ms");
}
}
static Boolean IsPrime(int x) {
if ((x & 1) == 0)
return x == 2;
if (x < 2)
return false;
for (int i = 3, s = (int)Math.Sqrt(x); i <= s; i += 2)
if (x % i == 0)
return false;
return true;
}
}
결과는 static Program program
속성에 대한 정적 생성자와 생성자 모두 그 Benchmark()
실행 거의 2 배 느리게 보여 여기
// static Program program = new Program()
public constructor:
2039 ms
2024 ms
2020 ms
2019 ms
2013 ms
static constructor:
2019 ms
2028 ms
2019 ms
2021 ms
2020 ms
main method:
1120 ms
1120 ms
1119 ms
1120 ms
1120 ms
// new Program() in Main()
public constructor:
1120 ms
1128 ms
1124 ms
1120 ms
1122 ms
왜 그렇습니까? 초기화가 속한 곳에서 완료되면 초기화가 빠르게 수행되는 것이 합리적입니다. 테스트는 .NET 4, 릴리스 모드, 최적화에서 수행되었습니다.
정확히 무엇이 문제입니까? – jcolebrand
설정을 컴파일 하시겠습니까? 프레임 워크 버전? – user7116
내 편집 내용이 마음에 들지 않는지 확인하십시오 (이유는 모르겠 음). NET 4/릴리스와 비슷한 결과를 얻었습니다. –