-->

Conditional statement order by frequency or comput

2020-07-27 06:06发布

问题:

Let's say I have 100 different conditions in a IF-ELSE statement.

if((boolean = methodA)){
    ...
}
else((boolean = methodZ)){
    ...
}

Logically, I think the least possible condition should go to the last condition(the one with methodZ) and the most frequent condition should go to ths first condition(methodA).

Then I thought "what if methodA takes a lot of time compute?". methodZ would take more time than to reach even if its least frequent. Should I order the conditions by its compute time? Or order them by just their frequency?

What would be a good approach to resolve this dilemma?

回答1:

Let's say I have 100 different conditions in a IF-ELSE statement

If you happen to do that in a real world application, then you have a huge design problem more important to solve than measure the time to evaluate the conditions.

Should I order the conditions by its compute time? Or order them by just their frequency?

There's no exact answer on this. The first thing to do is just write the conditions, then use a profiler in your application and evaluate if some of the conditions is really a problem in your code. If you spot one of these has lot of CPU usage, then start the specific analysis to enhance it.



回答2:

You need to strike the balance. The time to be calculated is not just for the methods but for the entire transaction. If the methodZ is finished in 1/100 of time of methodA and the frequency of methodZ is less than 100th of methodA, then it should be moved top.