我基準測試了此線程中提到的幾種方法(編輯:添加nr。 6)。
- 的List.exists方法(〜0.75秒)
- 的Set.contains方法(〜0.51秒)
- String.IndexOf(〜0.25秒)
- 非正則表達式編譯(〜 5 - 6秒)
- 編譯的正則表達式(〜1.0秒)
- 模式匹配(爲什麼我忘了這第一次)(〜0.17秒)
?
我用500000個隨機單詞填充了一個列表,並通過各種startsWithVowel函數過濾了它,重複了10次。
測試代碼:
open System.Text.RegularExpressions
let startsWithVowel1 =
let vowels = ['a';'e';'i';'o';'u']
fun (s:string) -> vowels |> List.exists (fun v -> s.[0] = v)
let startsWithVowel2 =
let vowels = ['a';'e';'i';'o';'u'] |> Set.ofList
fun (s:string) -> Set.contains s.[0] vowels
let startsWithVowel3 (s:string) = "aeiou".IndexOf(s.[0]) >= 0
let startsWithVowel4 str = Regex.IsMatch(str, "^[aeiou]")
let startsWithVowel5 =
let rex = new Regex("^[aeiou]",RegexOptions.Compiled)
fun (s:string) -> rex.IsMatch(s)
let startsWithVowel6 (s:string) =
match s.[0] with
| 'a' | 'e' | 'i' | 'o' | 'u' -> true
| _ -> false
//5x10^5 random words
let gibberish =
let R = new System.Random()
let (word:byte[]) = Array.zeroCreate 5
[for _ in 1..500000 ->
new string ([|for _ in 3..R.Next(4)+3 -> char (R.Next(26)+97)|])
]
//f = startsWithVowelX, use #time in F# interactive for the timing
let test f =
for _ in 1..10 do
gibberish |> List.filter f |> ignore
我卑微的結論: 編輯: 的
勢在必行的IndexOf
F#模式匹配贏得速度的較量。
Set.contains方法贏得選美比賽。
好主意。我只在我的回答中使用了List,因爲這是我們開始的。 Set對元音的意圖有更接近的含義。就表現而言,嗯,因爲收藏是如此之小。 – 2009-11-23 18:20:17