title: Simple: efficiency of ' if '
body: <p>I do not have a teacher who I can ask questions about efficiency, so I will ask it here.</p>
  
  <p>If I am only looking to have fast working code, not paying attention to ram use, only cpu:</p>
  
  <p>I assume that checking 'if' once is faster than writing a variable once. But what is the ratio? When is it worth always checking if the variable is not already at the value that I am going to set it to?</p>
  
  <p>For example:</p>
  
  <pre><code>//ex. 1
  int a = 5;
  while (true) {
      a = 5;
  }
  
  //ex. 2
  int a = 5;
  while (true) {
      if (a != 5) a = 5;
  }
  
  //ex. 3
  int a = 6;
  while (true) {
      if (a != 5) a = 5;
      a = 6;
  }
  </code></pre>
  
  <p>I guess ex. 2 will work faster than ex. 1 because 'a' always stays at '5'. In this case 'if' speeds up the process by not writing a new value to 'a' everytime. But if 'a' often changes, like in ex. 3, then checking if (a != 5) is not necessary and slows down the process. So this checking is worth it if the variable stays the same most of the time; and not worth it if the variable changes most of the time. But where is the ratio? Maybe writing a variable takes 1000 times more time than just checking it? Or maybe writing almost takes the same time as checking it? Im not asking for an exact answer, I just always wonder what is best for my code.</p>