2013-02-28 101 views
-2

最近我做了一個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]; 
} 

我沒想到,在這裏的代碼可以有任何關係,我問的問題,這就是爲什麼我之前沒有包括它,對不起。

+3

沒有實際的初始化代碼,我們該如何幫助你? – 2013-02-28 20:33:32

+1

請將代碼發佈到'doStuff()'。 – Asaph 2013-02-28 20:36:27

+1

而且「很糟糕」的速度有多慢?它確實不應該慢很多。 – 2013-02-28 20:37:15

回答

3

原因很慢是因爲doStuff()很慢。