2013-10-26 39 views
0

我做了一個vigenere加密/解密程序,似乎按照我的意圖工作,但是在非常大的文本文件(500,000字符aprox)上運行我的加密/解密需要2-4分鐘。我查看了我的代碼,看不到什麼操作可能會減慢速度。任何人有任何想法,我可以加快這一點?Java的vigenere密碼性能問題

代碼:

public static String encrypt(String text, String key) 
{ 
    String cipherText = ""; 
    text = text.toLowerCase(); 
    for(int i = 0; i < text.length(); i++) 
    { 
     System.out.println("Count: "+ i); //I just put this in to check the 
              //loop wasn't doing anything unexpected 
     int keyIndex = key.charAt(i%key.length()) - 'a'; 
     int textIndex = text.charAt(i) - 'a'; 
     if(text.charAt(i) >= 'a' && text.charAt(i) <= 'z') { //check letter is in alphabet 
      int vigenere = ((textIndex + keyIndex) % 26) + 'a'; 
      cipherText = cipherText + (char)vigenere; 
     } else 
      cipherText = cipherText + text.charAt(i); 
     } 

    } 
    return cipherText; 
} 

此前運行加密我有讀取文本文件使用掃描儀一個字符串的方法。此字符串加上預定義的鍵用於創建加密文本。

謝謝。

ANSWER

由於RC - 這是我的字符串連接抽空。如果其他人有興趣,這是我現在更新的代碼現在很快:

public static String encrypt(String text, String key) 
{ 
    StringBuilder cipher = new StringBuilder(); 
    for(int i = 0; i < text.length(); i++) 
    { 
     int keyIndex = key.charAt(i%key.length()) - 'a'; 
     int textIndex = text.charAt(i) - 'a'; 
     if(text.charAt(i) >= 'a' && text.charAt(i) <= 'z') { 
      int vigenere = ((textIndex + keyIndex) % 26) + 'a'; 
      cipher.append((char)vigenere); 
     } else { 
      cipher.append(text.charAt(i)); 
     } 

    } 
    return cipher.toString(); 
} 
+0

使用StringBuilder進行字符串連接 – 2013-10-26 13:01:56

+0

非常感謝!所以我假設沒有使用,它只是爲每個添加的字符重新創建一個新的字符串,因此隨着字符串變長,每次迭代需要的時間越來越長。再次感謝 – gdm181

+0

不客氣。 – 2013-10-26 14:55:27

回答

0

附加到StringBuilder,而不是創建新的String實例。 你想要做一個

buffer.append((char)vigenere); 

代替cipherText = cipherText + (char)vigenere;

0

目前你正在做

for(int i = 0; i < text.length(); i++){ 
    ... 
    int keyIndex = key.charAt(i%key.length()) - 'a'; 
    ... 
} 

你可以嘗試從for -loop刪除keyIndex的calucation實現它在預處理步驟中。例如,您可以將keyIndex值/字符存儲在單獨的數組中,並訪問原始循環中的數組內容。這應該爲您節省一些計算步驟。