PFr*_*ise 12 java optimization if-statement
我有几个案例,我只是使用简单的if ... if else
块.
如何减少if
此代码中的语句数量?
也许我可以使用查找表,但我不确定如何在Java中实现它.
private int transition(char current, int state)
{
if(state == 0)
{
if(current == 'b')
{
return 1;
}
else
return 0;
}
if(state == 1)
{
if(current == 'a')
{
return 2;
}
else
return 0;
}
if(state == 2)
{
if(current == 's')
{
return 3;
}
else
return 0;
}
if(state == 3)
{
if(current == 'e')
{
return 3;
}
if(current == 'b')
{
return 4;
}
else
return 0;
}
if(state == 4)
{
if(current == 'a')
{
return 5;
}
else
return 0;
}
if(state == 5)
{
if(current == 'l')
{
return 6;
}
else
return 0;
}
else
return 0;
}
Run Code Online (Sandbox Code Playgroud)
cas*_*nca 32
你要做的事情看起来非常像有限状态机,这些通常是在转换表的帮助下实现的.设置表后,只需索引到想要获得返回值的位置即可.假设返回值都小于256,则可以使用2D字节数组:
byte table[][] = new byte[NUM_STATES][NUM_CHARACTERS];
// Populate the non-zero entries of the table
table[0]['b'] = 1;
table[1]['a'] = 2;
// etc...
private int transition(char current, int state) {
return table[state][current];
}
Run Code Online (Sandbox Code Playgroud)
Nik*_*bak 14
好吧,你可以轻松利用哈希.简单干净.
// declare hashtable
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("0-b", 1);
map.put("1-a", 2);
map.put("2-s", 3);
...
// get result
Integer result = map.get(state + "-" + current);
// change null (nothing found) to zero
return result == null ? 0 : result;
Run Code Online (Sandbox Code Playgroud)
考虑接口+枚举:
interface State<T>
{
public void State<T> step(T input);
}
enum MyState implements State<Character> {
STATE0(0) { @Override public void MyState step(Character c) { return c == 'b' ? STATE1 : STATE0; }},
STATE1(1) { @Override public void MyState step(Character c) { return c == 'a' ? STATE2 : STATE0; }},
/* rest of states here */
final private int value;
MyState(int value) { this.value = value; }
public int getValue() { return this.value; }
}
class SomeClass
{
public MyState currentState = STATE0;
public void step(char input)
{
this.currentState = this.currentState.step(input);
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里切换语句最好:
private int transition(char current, int state)
{
switch(state)
{
case 0:
return current == 'b' ? 1 : 0;
case 1:
return current == 'a' ? 2 : 0;
case 2:
return current == 's' ? 3 : 0;
case 3:
return current == 'e' ? 3 : (current == 'b' ? 4 : 0);
case 4:
return current == 'a' ? 5 : 0;
case 5:
return current == 'l' ? 6 : 0;
default:
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
还有一个注释,只有5个if语句检查纯粹的整数,这不是一个开销.
看起来你需要为有限状态机提供更好的抽象.考虑一个以更好的方式封装您想要的内容的类,以便您可以通过配置而不是修改代码来扩展它.