为什么使用Singleton在Java中创建对象太慢了?
问题描述:
最近我做了一个Singleton类,其中有一个方法返回Singleton类的对象myInstance
。它是这样的:为什么使用Singleton在Java中创建对象太慢了?
private final static Singleton myInstance = new Singleton();
,我整个编码构造,这是私人后,让说:
private Singleton(){
doStuff()
}
但是表现得可怕。也许有人可以给我一个暗示,为什么doStuff()
比我不使用Singleton时慢得多?我想这与在声明变量时调用构造函数有关,但有人可以分享一些关于它的信息吗?
我不知道这是为什么,我试图寻找解释,但我找不到它。
编辑:dostuff函数包括诸如打开文件/读取它们/使用regexp对它们使用levenstein函数[由profiler是代码最慢的部分]。 在使用单例时从构造函数运行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()
很慢。
没有实际的初始化代码,我们该如何帮助你? – 2013-02-28 20:33:32
请将代码发布到'doStuff()'。 – Asaph 2013-02-28 20:36:27
而且“很糟糕”的速度有多慢?它确实不应该慢很多。 – 2013-02-28 20:37:15