1 people like it.

Faster Filter 2

Another faster filter. Faster in almost all circumstances for sufficiently simple predicates. Not as fast as http://www.fssnip.net/7Qp but does not require the hacky ThreadLocal ResizeArray.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
let inline filter (f: ^T -> bool) (array: ( ^T)[]) = 
    
    if array = null then invalidArg "array" "Array can not be null."            
    if array.Length = 0 then invalidArg "array" "Array can not be empty."    
        
    let mutable count = 0

    for i = 0 to array.Length-1 do
        if f array.[i] then
            count <- count + 1
                    
    let result = Array.zeroCreate count
    let mutable j = 0
    for i = 0 to array.Length-1 do
        if f array.[i] then
            result.[j] <- array.[i]
            j <- j + 1
    result
val filter : f:('T -> bool) -> array:'T [] -> 'T [] (requires equality)

Full name: Script.filter
val f : ('T -> bool) (requires equality)
type bool = System.Boolean

Full name: Microsoft.FSharp.Core.bool
Multiple items
val array : 'T [] (requires equality)

--------------------
type 'T array = 'T []

Full name: Microsoft.FSharp.Core.array<_>
val invalidArg : argumentName:string -> message:string -> 'T

Full name: Microsoft.FSharp.Core.Operators.invalidArg
property System.Array.Length: int
val mutable count : int
val i : int
val result : 'T [] (requires equality)
module Array

from Microsoft.FSharp.Collections
val zeroCreate : count:int -> 'T []

Full name: Microsoft.FSharp.Collections.Array.zeroCreate
val mutable j : int

More information

Link:http://fssnip.net/7Qq
Posted:8 years ago
Author:Jack Mott
Tags: filter