如果陈述速度问题 [英] If statement speed question

查看:65
本文介绍了如果陈述速度问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对跑步速度有疑问.是这个吗?

I have a question about run speed. Is this:

if( (x1 == x2) && (x2 == x3) && (x3 == x4) && (x4 == x5) ) return true;
else
    return false;



更快,更慢或与此大致相同:



faster, slower or about the same as this:

if( x == x2)
{
    if( x2 == x3)
        if(x3 == x4)
            if(x4 == x5)
                return true;
}
else
    return false;

推荐答案

请确保重复几次计时实验,因为测量值会发生波动.

在已编译的代码中,没有理由不应该改变速度,它们将转换为完全相同的汇编代码.

您也可以写

Be sure to repeat the timing experiment several times because the measurements will fluctuate.

In compiled code, there is no reason the speeds should be different, they will translate to exactly the same assembly code.

You could also write

return x1 == x2 && x2 == x3 && x3 == x4 && x4 == x5;


相同的速度.

可能略有不同,但效果相同:


same speed.

And possibly slightly different speed but same effect:

return x1 == x2 && x1 == x3 && x1 == x4 && x1 == x5;



如果x是整数,那么当然值得尝试:



If the x''s are integers, it is certainly worth to try:

return ((x1 ^ x2) | (x2 ^ x3) | (x3 ^ x4) | (x4 ^ x5)) == 0;


/// <summary>
/// Performance Counter to calculate function executing time.
/// </summary>
public class Performance
{
    public delegate void CalculateHanlder();
    /// <summary>
    /// Using Performance.CalculFunction(MethodName)
    /// It will print executing time in Console.
    /// </summary>
    /// <param name="method">A none argument method</param>
    public static void CalculateMethod(CalculateHanlder method)
    {
        Stopwatch st = new Stopwatch();
        st.Start();
        method.Invoke();
        st.Stop();
        string msg = string.Format("Elapsed = {0} in [{1}]", st.Elapsed.ToString(), method.Method.ToString());
        Console.WriteLine(msg);
        Debug.WriteLine(msg);
    }
}
bool Test(int x1, int x2, int x3, int x4, int x5)
{
if( (x1 == x2) && (x2 == x3) && (x3 == x4) && (x4 == x5) ) return true;
else
    return false;
}
bool Test2(int x1, int x2, int x3, int x4, int x5)
{
if( x == x2)
{
    if( x2 == x3)
        if(x3 == x4)
            if(x4 == x5)
                return true;
}
else
    return false;
}
void TestIf()
{
    for(int i = 0 ; i < 100000; i ++)
        Test(1,2,3,4,5);
}
Performance.CalculateMethod(TestIf);


您可以使用这些代码进行测试.
使用StopWatch可以计算执行时间.
这是我的库函数,您可以传递一个无参数函数来打勾.


You can use these code to test.
Using StopWatch can count the executing time.
This is my library function, you can pass a none parameter function to tick.


尝试一下.你可以学到一些东西
Try it and see. You could learn something


这篇关于如果陈述速度问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆