Tôi biết đây là một câu hỏi cũ, nhưng tôi figured tôi muốn ném ra một giải pháp đơn giản mà dường như hoạt động tốt và duy trì hiệu
static void Main(string[] args)
{
int loopCount = 1000000; // 1,000,000 (one million) iterations
var timer = new Timer();
timer.Restart();
for (int i = 0; i < loopCount; i++)
Log(MethodBase.GetCurrentMethod(), "whee");
TimeSpan reflectionRunTime = timer.CalculateTime();
timer.Restart();
for (int i = 0; i < loopCount; i++)
Log((Action<string[]>)Main, "whee");
TimeSpan lookupRunTime = timer.CalculateTime();
Console.WriteLine("Reflection Time: {0}ms", reflectionRunTime.TotalMilliseconds);
Console.WriteLine(" Lookup Time: {0}ms", lookupRunTime.TotalMilliseconds);
Console.WriteLine();
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
}
public static void Log(Delegate info, string message)
{
// do stuff
}
public static void Log(MethodBase info, string message)
{
// do stuff
}
public class Timer
{
private DateTime _startTime;
public void Restart()
{
_startTime = DateTime.Now;
}
public TimeSpan CalculateTime()
{
return DateTime.Now.Subtract(_startTime);
}
}
Chạy mã này mang lại cho tôi kết quả như sau:
Reflection Time: 1692.1692ms
Lookup Time: 19.0019ms
Press Enter to exit
Đối với một triệu lần lặp lại, điều đó không tệ ở tất cả, đặc biệt là so với phản xạ thẳng lên. Nhóm phương thức đang được truyền đến một loại đại biểu, bạn duy trì một liên kết tượng trưng tất cả các cách vào khai thác gỗ. Không có dây ma thuật ngốc nghếch.
@loannis, câu hỏi tương tự được hỏi tại đây. Kiểm tra liên kết http://stackoverflow.com/questions/1466740/using-getcurrentmethod-in-supposedly-high-performance-code – RameshVel
Từ daniels trả lời "this.GetType() yêu cầu 2,5 ns cho mỗi cuộc gọi trong khi MethodBase.GetCurrentMethod() .DeclaringType yêu cầu 2490 ns cho mỗi cuộc gọi - vì vậy bạn có tốc độ tăng khoảng 1200. " – RameshVel
@Ramesh: Bạn có nhận thấy đó chính xác là (các) câu hỏi mà anh ta đã liên kết trong câu hỏi không? –