2011-03-16 55 views
5

我有修正資本化,資本化異常單詞列表功能:JavaScript正則表達式性能。

var line = "some long string of text"; 
["AppleScript", "Bluetooth", "DivX", "FireWire", "GarageBand", 
"iPhone", "iTunes", "iWeb", "iWork", "JavaScript", "jQuery", "MacBook", 
"MySQL", "PowerBook", "PowerPoint", "QuickTime", "TextEdit", "TextMate", 
// ... 
"Wi-Fi", "Xcode", "Xserve", "XMLHttpRequest"].forEach(function(name) { 
     line = line.replace(RegExp(name, "gi"), name); 
}); 

現在我面臨的問題是,大多數輸入字符串將包含平均介於0和這些詞3之間。顯然,現在我做了幾十個(可能有幾百個;這個數組有着不可思議的隨時間增長的趨勢)函數調用,它本質上什麼都不做。

如何讓此代碼更快並擺脫不必要的函數調用?

示例輸入:

我的iPhone應用程序具有的UIViewController下一個用戶的形式。當我再次啓動應用程序時,我的一些UIView會改變它的位置和大小。 (這些UIViews取決於鍵盤的位置)某處肯定是我的錯。我試圖找出當應用程序從後臺重新啓動並且可以完成UIView更改時發生了什麼。

+0

電話不是不必要的嗎?如果你想檢查大寫每個字符串,那麼你需要檢查每一個...只是因爲它不存在並不意味着檢查沒有必要... – 2011-03-16 11:54:45

+0

@Sam但是必要的整個輸入?或者可以創建一個更智能的正則表達式來完成一次函數調用中的所有檢查? – 2011-03-16 11:59:31

+0

好的,我明白你的觀點。 – 2011-03-16 12:04:35

回答

5

你可以建立一個包含所有你的話,用括號括起來捕捉每一個字正則表達式。在替換中使用它將提供足夠的信息來恢復替換函數中的原始單詞。

function correct (text, words) { 
    return text.replace (RegExp ('\\b(?:(' + words.join (')|(') + '))\\b', 'ig'), function (m) { 
     for (var a = arguments.length - 2; a--;) 
     if (arguments[a]) 
     return words[a-1] || m; 
    }); 
    } 

    console.log (correct ("My iphone itunes divx firewire application has a user form under uiviewcontroller. When I start application again some of my uiview changes its positions and sizes. (These uiviews depend on keyboard position) Somewhere is definitely my fault. I try to figure what is going on when application starts again from background and where the uiview changes can be done.", 
    ["AppleScript", "Bluetooth", "DivX", "FireWire", "GarageBand", 
"iPhone", "iTunes", "iWeb", "iWork", "JavaScript", "jQuery", "MacBook", 
"MySQL", "PowerBook", "PowerPoint", "QuickTime", "TextEdit", "TextMate", 
// ... 
"UIViewController","UIView", 
"Wi-Fi", "Xcode", "Xserve", "XMLHttpRequest"])); 
My iPhone iTunes DivX FireWire application has a user form under UIViewController. When I start application again some of my UIView changes its positions and sizes. (These UIViews depend on keyboard position) Somewhere is definitely my fault. I try to figure what is going on when application starts again from background and where the UIView changes can be done. 

This turns out to be faster then the original code

+0

現在這會比我現在的代碼更快嗎?爲什麼? – 2011-03-16 13:09:07

+0

這個函數調用的次數是2 +(number_of_words_replaced)。其餘的繁重工作由快速的內部功能完成。如果單詞數組是靜態的,你可以消除每次調用時的正則表達式構建 – HBP 2011-03-16 13:44:18

+1

正則表達式需要稍微修改,因爲它然後在單詞內匹配:'RegExp('\\ b(?:('+ words.join(')| (')+'))\\ b','ig')'這樣做。 – 2011-03-16 14:31:16