开发者

Can I use variables to replace If conditions?

Since I need j%3 and j%5 to use in three places, I used it like a variable, I just want to know, is this reduce any memory storage and increase efficiency,

private void forloo()
        {
            bool a = j % 3 == 0;
            bool b = j % 5 == 0;
            for (int i=0; i < j; i++)
            {
                if (a&&b开发者_C百科)
                {
                    richTextBox1.Text += "Hop\n";
                }

                if (a)
                {
                    richTextBox1.Text += "Hoppity\n";

                }
                else if (b)
                {
                    richTextBox1.Text  += "HopHop\n";
                }
            }
        }


If you are implementing a FizzBuzz program, you need to check if i is divisible by 3 and 5, not j.

Any optimizer is going to see the common subexpressions and not keep recalculating it. However, it's usual to want to use a variable for readability. In that case, a and b aren't good enough names.


In this case, you probably won't see much increase in performance if this isn't done so often. If the booleans were more complex, or contained calls to other functions, you would be better off storing them in a variable.

The effects on memory are negligible for a bool.


In your case you really don't need the to have your multiple if statements inside the loop. Write it as:

    private void forloo()
    {
        bool a = j % 3 == 0;
        bool b = j % 5 == 0;
        string text = string.Empty;
        if (a&&b)
        {
            text = "Hop\n";
        }
        if (a)
        {
            text = "Hoppity\n";

        }
        else if (b)
        {
            text  = "HopHop\n";
        }
        for (int i=0; i < j; i++)
        {
            richTextBox1.Text += text;
        }
    }

But as the answer by Lou Franco says you're probably doing the wrong thing.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜