为什么在Java中使用Singleton创建对象会这么慢



最近我创建了一个类Singleton,其中有一个方法返回类Singleton的对象myInstance。它是这样的:

private final static Singleton myInstance = new Singleton();

之后,我编写了整个构造函数,它是私有的,比如:

private Singleton(){
   doStuff()
}

但是表演很糟糕。也许有人能给我一个提示,为什么doStuff()比我不使用单例时慢得多?我猜这与声明变量时调用构造函数有关,但有人能分享一些信息吗?

我不知道为什么,我试图寻找解释,但我找不到。

编辑:dostuff函数包括打开文件/读取文件/对文件使用regexp,使用levenstein函数[被分析器认为是代码中最慢的部分]。当使用singleton从构造函数运行levenstein时,levenstein函数的速度大约需要10秒。对象创建之后,在这个单例对象中调用这个函数只需要0.5秒。现在,当不使用单例时,从构造函数调用levenstein函数也需要0.5秒,而单例调用levenstein函数需要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()慢。

最新更新