Last active
August 8, 2016 15:18
-
-
Save jackmott/12d25d6b3f9a7c2aaf1b0bdb9bbd7849 to your computer and use it in GitHub Desktop.
Fast Filter for F#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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