最近、私はクラスSingletonを作成しました。これは、クラスSingletonのオブジェクトを返すメソッドでしたmyInstance
。それは次のようなものでした:
private final static Singleton myInstance = new Singleton();
その後、プライベートであるコンストラクター全体をコーディングしました。
private Singleton(){
doStuff()
}
しかし、パフォーマンスはひどいものでした。doStuff()
シングルトンを使用しない場合に、なぜはるかに遅いのか、誰かが私にヒントを与えることができるかもしれません。変数を宣言しているときにコンストラクターを呼び出すことと関係があると思いますが、誰かがそれに関する情報を共有できますか?
なぜなのかわからないので、説明を探してみましたが見つかりませんでした。
編集:dostuff関数には、ファイルを開く/読み取る/正規表現を使用する、levenstein関数を使用する[プロファイラーによるコードの最も遅い部分]などが含まれます。シングルトンを使用しながらコンストラクターからそのlevensteinを実行すると、levenstein関数の速度は約10秒かかりました。オブジェクトが作成された後、このシングルトンオブジェクト内のこの関数の呼び出しはわずか0.5秒で完了しました。現在、シングルトンを使用していない場合、コンストラクターからのlevenstein関数の呼び出しも0.5秒であり、シングルトンによって実行されたときの10秒より前です。関数のコードは次のとおりです。["odleglosci"は単なるマップです]
private static int getLevenshteinDistance(String s, String t) {
int n = s.length(); // length of s
int m = t.length(); // length of t
int p[] = new int[n + 1]; //'previous' cost array, horizontally
int d[] = new int[n + 1]; // cost array, horizontally
int _d[]; //placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i <= n; i++) {
p[i] = i * 2;
}
int add = 2;//how much to add per increase
char[] c = new char[2];
String st;
for (j = 1; j <= m; j++) {
t_j = t.charAt(j - 1);
d[0] = j;
for (i = 1; i <= n; i++) {
cost = s.charAt(i - 1) == t_j ? 0 : Math.min(i, j) > 1 ? (s.charAt(i - 1) == t.charAt(j - 2) ? (s.charAt(i - 2) == t.charAt(j - 1) ? 0 : 1) : 1) : 1;//poprawa w celu zmniejszenia wartosci czeskiego bledu
if (cost == 1) {
c[0] = s.charAt(i - 1);
c[1] = t_j;
st = new String(c);
if (!odleglosci.containsKey(st)) {
//print((int) c[0]);
//print((int) c[1]);
} else if (odleglosci.get(st) > 1) {
cost = 2;
}
} else {
c[0] = s.charAt(i - 1);
c[1] = t_j;
st = new String(c);
if (!odleglosci.containsKey(st)) {
// print((int) c[0]);
// print((int) c[1]);
} else if (odleglosci.get(st) > 1) {
cost = -1;
}
}
d[i] = Math.min(Math.min(d[i - 1] + 2, p[i] + 2), p[i - 1] + cost);
}
_d = p;
p = d;
d = _d;
}
return p[n];
}
ここにあるコードが私が尋ねた質問に関連しているとは思わなかったので、申し訳ありませんが、以前はコードを含めませんでした。