开发者

First-Time Indexing arrays is way too slow

I am writing an application using C#. I ran some benchmarks to try and speed up my application and came accross a problem. I have a loop which needs to run multiple times at separate intervals:

Process[] processes = Process.GetProcesses();
foreach (Process process in processes)
    if (process.MainWindowTitle == "Title")
    {
        // Do Stuff
    }

I realized that the problem is, as soon as I create the array, accessing a specific element of that array takes significantly longer than subsequent access.

if (processes[0].MainWindowTitle == "Title") { } // ~0.5 ms
if (processes[0].MainWindowTitle == "Title") { } // ~0.0 ms
if (processes[0].MainWindowTitle == "Ti开发者_如何学Gotle") { } // ~0.0 ms
if (processes[0].MainWindowTitle == "Title") { } // ~0.0 ms

This is quite a significant problem. Something that should be taking less than 0.1ms is taking 50ms. Why is this happening and what can I can do to speed things up?


It's not accessing the array which is slow - it's getting the MainWindowTitle property, which I believe is lazily populated. When you first ask for it, it's doing all the OS gubbins to fetch the value.

To test this, try:

if (processes[0] != null)

which I think you'll find will be very fast right from the start.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜