2

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)
                {
                    richTextBox1.Text += "Hop\n";
                }

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

                }
                else if (b)
                {
                    richTextBox1.Text  += "HopHop\n";
                }
            }
        }
2
  • Yes, as you can presumably see by compiling it and running it, your program works the same. Commented Dec 28, 2010 at 22:04
  • 1
    I would be more worried about the += on two strings (as opposed to using a StringBuidler) rather than an arithmetic-boolean equality. I would say the difference in performance is near none. Commented Dec 28, 2010 at 22:16

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1: You also need to put a =... and b =... inside the scope of the for loop.
+1 for the last two sentences; when we are discussing differences of literally a thousandth-of-a-thousandth-of-a-thousandth of a second, nobody cares which is more efficient. What really matters is writing better code.
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.