Note that there are some explanatory texts on larger screens.

plurals
  1. POFaster parsing of numbers on .NET
    primarykey
    data
    text
    <p>I have written two functions that convert a string of whitespace-separated integers into an int array. The first function uses <code>Substring</code> and then applies <code>System.Int32.Parse</code> to convert the substring into an <code>int</code> value:</p> <pre class="lang-ml prettyprint-override"><code>let intsOfString (s: string) = let ints = ResizeArray() let rec inside i j = if j = s.Length then ints.Add(s.Substring(i, j-i) |&gt; System.Int32.Parse) else let c = s.[j] if '0' &lt;= c &amp;&amp; c &lt;= '9' then inside i (j+1) else ints.Add(s.Substring(i, j-i) |&gt; System.Int32.Parse) outside (j+1) and outside i = if i &lt; s.Length then let c = s.[i] if '0' &lt;= c &amp;&amp; c &lt;= '9' then inside i (i+1) else outside (i+1) outside 0 ints.ToArray() </code></pre> <p>The second function traverses the characters of the string in-place accumulating the integer without creating a temporary substring:</p> <pre class="lang-ml prettyprint-override"><code>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' &lt;= c &amp;&amp; c &lt;= '9' then inside (10*n + int c - 48) (i+1) else ints.Add n outside(i+1) and outside i = if i &lt; s.Length then let c = s.[i] if '0' &lt;= c &amp;&amp; c &lt;= '9' then inside (int c - 48) (i+1) else outside (i+1) outside 0 ints.ToArray() </code></pre> <p>Benchmarking on space-separated integers 1 to 1,000,000, the first version takes 1.5s whereas the second version takes 0.3s.</p> <p>Parsing such values can be performance critical so leaving 5x performance on the table by using temporary substrings can be undesirable. Parsing integers is easy but parsing other values such as floating point numbers, decimals and dates is considerably harder.</p> <p>So, are there built-in functions to parse directly from a substring within a string (i.e. using the given start and length of a string) in order to avoid generating a temporary string? If not, are there any libraries that provide efficient functions to do this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload