Monday, 6 January 2014

Parsing ints quickly

The built-in .NET library functions for parsing integers are very easy to use but a lower-level approach can be around 6x faster. Here is a function that parses a sequence of 32-bit integers:

  let intsOfString (s: string) =
    let ints = ResizeArray()
    let rec inside n i =
      if i = s.Length then
        ints.Add n
      else
        let c = s.[i]
        if '0' <= c && c <= '9' then
          inside (10*n + int c - 48) (i+1)
        else
          ints.Add n
          outside(i+1)
    and outside i =
      if i < s.Length then
        let c = s.[i]
        if '0' <= c && c <= '9' then
          inside (int c - 48) (i+1)
        else
          outside (i+1)
    outside 0
    ints.ToArray()

For example:

> intsOfString "123 456 789";;
val it : int [] = [|123; 456; 789|]

No comments: