user2757036
user2757036

Reputation: 47

Simple: efficiency of ' if '

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.

Upvotes: 2

Views: 111

Answers (1)

Kayaman
Kayaman

Reputation: 73578

Short answer: it doesn't matter.

Long answer: It really doesn't matter at that low level. Even if you were to actually compare the executed machine code, there are so many things in between (the JIT compiler for one, all sorts of CPU caches for other).

Gone are the times when you needed to micro-optimize things like this. What you need to make sure is that you're using effective algorithms. And as always, premature optimization is the root of all evil.

I noted that you wrote "I just always wonder what is the best way for my code". The best way is to write clear code, so that other people can understand what you're doing (if they saw code like in your examples, they would think you're insane). Another old adage was that in order for the JVM to optimize your code in the best way, you should write "dumb code". The JIT optimizer can then understand the code better and convert it to a more efficient form.

Upvotes: 8

Related Questions