Skip to content

Instantly share code, notes, and snippets.

@jackmott
Last active August 8, 2016 15:18
Show Gist options
  • Save jackmott/12d25d6b3f9a7c2aaf1b0bdb9bbd7849 to your computer and use it in GitHub Desktop.
Save jackmott/12d25d6b3f9a7c2aaf1b0bdb9bbd7849 to your computer and use it in GitHub Desktop.
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