【发布时间】:2013-02-28 20:32:25
【问题描述】:
最近我做了一个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];
}
我没想到这里的代码可能与我提出的问题有任何关系,所以我之前没有包含它,对不起。
【问题讨论】:
-
没有实际的初始化代码,我们应该如何帮助您?
-
请将代码发布到
doStuff()。 -
“可怕”到底有多慢?它真的不应该显着变慢。
-
您是否真的使用分析器来验证这一点?
-
我称其为编程之神对徒劳召唤单身人士的报应。
标签: java performance constructor singleton