I do not have a teacher who I can ask questions about efficiency, so I will ask it here.
If I am only looking to have fast working code, not paying attention to ram use, only cpu:
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?
For example:
//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;
}
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.