Conditional statement order by frequency or compute time?

人盡茶涼 提交于 2019-12-12 09:15:43

问题


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.



来源:https://stackoverflow.com/questions/18757692/conditional-statement-order-by-frequency-or-compute-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!