ユーザーが入力する単純な数学関数をグラフ化する Android アプリを作成しようとしています (基本的にグラフ電卓)。すべての onDraw 呼び出しには、毎秒数百回の算術評価が必要です (グラフを生成するために画面にプロットされます)。私のコードが式を評価すると、プログラムの速度が大幅に低下します。組み込みメソッドが式を評価すると、アプリは問題なく実行されます。
「LogCat」によると、ガベージ コレクションは 1 秒あたり約 12 回発生し、そのたびに約 15 ミリ秒間アプリが一時停止し、毎秒数百ミリ秒相当のフリーズが発生します。これが問題だと思います。
これは、私のエバリュエーター関数の蒸留バージョンです。評価される式は「postfixEquation」という名前で、文字列 ArrayList の「リスト」はプロセスの最後に最終的な答えを保持します。使用可能な数字と記号を格納する「数字」と「演算子」という名前の 2 つの文字列配列もあります。
String evaluate(String[] postfixEquation) {
list.clear();
for (int i = 0; i < postfixEquation.length; i++) {
symbol = postfixEquation[i];
// If the first character of our symbol is a digit, our symbol is a numeral
if (Arrays.asList(digits).contains(Character.toString(symbol.charAt(0)))) {
list.add(symbol);
} else if (Arrays.asList(operators).contains(symbol)) {
// There must be at least 2 numerals to operate on
if (list.size() < 2) {
return "Error, Incorrect operator usage.";
}
// Operates on the top two numerals of the list, then removes them
// Adds the answer of the operation to the list
firstItem = Double.parseDouble(list.get(list.size() - 1));
secondItem = Double.parseDouble(list.get(list.size() - 2));
list.remove(list.size() - 1);
list.remove(list.size() - 1);
if (symbol.equals(operators[0])){
list.add( Double.toString(secondItem - firstItem) );
} else if (symbol.equals(operators[1])) {
list.add( Double.toString(secondItem + firstItem) );
} else if (symbol.equals(operators[2])) {
list.add( Double.toString(secondItem * firstItem) );
} else if (symbol.equals(operators[3])) {
if (firstItem != 0) {
list.add( Double.toString(secondItem / firstItem) );
} else {
return "Error, Dividing by 0 is undefined.";
}
} else {
return "Error, Unknown symbol '" + symbol + "'.";
}
}
}
// The list should contain a single item, the final answer
if (list.size() != 1) {
return "Error, " + list has " + list.size() + " items left instead of 1.";
}
// All is fine, return the final answer
return list.get(0);
}
操作で使用される数値はすべて文字列です。1 つの配列内に複数の型 (つまり、文字列と倍精度型) を保持できるかどうかわからなかったため、"Double.parseDouble" と "Double.toString" 呼び出しが横行しています。
ここで発生するガベージ コレクションの量を減らすにはどうすればよいでしょうか。
それが助けになる場合は、次の手順を使用して後置式を評価しています: http://scriptasylum.com/tutorials/infix_postfix/algorithms/postfix-evaluation/index.htm。私は何週間も何週間もこの問題を乗り越えることができませんでした. どんな助けでも大歓迎です。ありがとう。