Skip to content

Instantly share code, notes, and snippets.

@jackmott jackmott/fastFilter.fs
Last active Aug 8, 2016

Embed
What would you like to do?
Fast Filter for F#
// Faster than the core lib filter in most scenarios.
// Core lib may be faster when filtering about half the data
// and the filtered data is randomy distributed in the array.
// Even in cases where it is a little slower, it allocates a lot
// less. Relieving GC overhead.
let inline filter (f: ^T -> bool) (array: ( ^T)[]) =
let len = array.Length
if array = null then invalidArg "array" "Array can not be null."
if len = 0 then invalidArg "array" "Array can not be empty."
let mutable count = 0
let temp = Array.zeroCreate len
for i = 0 to array.Length-1 do
let b = f array.[i]
if b then
temp.[i] <- b
count <- count + 1
let result = Array.zeroCreate count
let mutable j = 0
for i = 0 to array.Length-1 do
if temp.[i] then
result.[j] <- array.[i]
j <- j + 1
result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.