条件语句按频率还是计算时间排序? [英] Conditional statement order by frequency or compute time?
问题描述
假设我在IF-ELSE语句中有100个不同的条件.
Let's say I have 100 different conditions in a IF-ELSE statement.
if((boolean = methodA)){
...
}
else((boolean = methodZ)){
...
}
从逻辑上讲,我认为最小可能的条件应该转到最后一个条件(使用methodZ的条件),而最频繁的条件应该转到第一个条件(方法A).
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).
然后我想如果methodA需要大量时间来计算会怎样?".即使不经常使用methodZ,也要花很多时间才能到达.我应该按其计算时间来排序条件吗?还是仅按频率订购?
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?
推荐答案
假设我在IF-ELSE语句中有100个不同的条件
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?
对此没有确切答案.首先要做的就是写条件,然后在您的计算机中使用分析器应用程序并评估某些条件是否确实在您的代码中有问题.如果您发现其中之一具有大量CPU使用率,请开始进行特定分析以增强它.
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.
这篇关于条件语句按频率还是计算时间排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!