int count()
{
return 5;
}
int variable = count();
switch(variable)
{
} //this works correct
switch(count())
{
}//this also works correct.
但是这些是正确的方法,两者之间的性能比较是什么? switch语句总是只需要一个参数吗?
答案 0 :(得分:2)
但其中哪一项是正确的方法
这两种方法都没有错。 switch(count())
比switch(variable)
简洁得多。
声明变量可能会使代码更具可读性,例如
final int month = Integer.parseInt(dateMonthYearString.split("/")[1]);
switch(month){/*...*/}
这两者之间的性能比较是什么?
我怀疑性能会有什么不同。当然不值得担心。
switch语句是否总是只需要一个显式参数?
我不确定你的意思。 switch
语句中的表达式必须评估为int
,short
,byte
,char
或enum
。从Java 1.7开始,表达式也可能返回String
。
答案 1 :(得分:0)
最后一个语句更好,因为count()只被调用一次。
在OOP中,您可以避免在某些情况下使用设计模式状态的开关,以获得比这两者更好的性能。 “用多态性替换开关/案例”是一种适用于您的参考的技术。