0

我已经编写了我的桌面应用程序,但有时它有点慢,所以我试图尽可能地优化它。问题是我不知道怎么做。

这是我有疑问的代码

if (((mainRibbonForm)Parent.Parent.Parent.Parent.Parent.Parent.Parent)).myParentScopeVar == false)
{
   //something goes here

}

//VS

if (myLocalScopeVar == false)
{
    //something goes here
}

所有对象都是在 mainRibbonForm 中创建并分配的,看来我不能这样调用。

mainRibbonForm.myparentScopeVar == false

因此,在最后一个对象中,我只是向后走,使用 Parent 命令变量来获取变量。

我不确定是否应该始终查看变量的父范围或将变量作为局部范围分配给最后一个控件,并且仅在父范围变量更改时才更新它,这并不经常发生,但确实发生了变化。

我在计时器中有一些这些,并且在代码中的每个地方都有。我对 C# 非常陌生,我将所有内容从 VB.Net 翻译成 C# 我只是想学习正确或最佳的 C# 编程实践

哪个更快并且使用更少的资源?

下次我如何自己进行基准测试?

4

1 回答 1

1

我认为这段代码太过分了,而且看起来很可怕:

if (((mainRibbonForm)Parent.Parent.Parent.Parent.Parent.Parent.Parent)).myParentScopeVar == false)
{
   //something goes here   
}

而不是这个,我更喜欢使用静态变量,然后使用mainRibbonForm.myParentScopeVar. 所以你可以在你的类中插入这个:

public static bool myParentScopeVar;

或者你可以通过构造函数传递这个布尔值。


如果您想进行基准测试,请使用作为Stopwatch高分辨率计时器的类来测量您的代码将运行多长时间并循环您正在测试的代码更多次以获得包括他的最佳和最差性能的中等时间:

Stopwatch timer = new Stopwatch();
timer.Start();

for(int i = 0; i < 1000; i++)
{
    if (((mainRibbonForm)Parent.Parent.Parent.Parent.Parent.Parent.Parent)).myParentScopeVar == false)
    {
         //something goes here   
    }
}

timer.Stop();  
TimeSpan timespan = timer.Elapsed;

MessageBox.Show(String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds / 10));    

timer.Restart();

for(int i = 0; i < 1000; i++)
{
    if (myLocalScopeVar == false)
    {
         //something goes here
    }
}

timer.Stop();  
TimeSpan timespan = timer.Elapsed;

MessageBox.Show(String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds / 10)); 

我认为我的解决方案和您使用的第二个解决方案myLocalScopeVar更有效。

于 2012-09-01T21:04:26.247 回答