Note that there are some explanatory texts on larger screens.

plurals
  1. POLINQ query is slow
    primarykey
    data
    text
    <p>During application profiling I found that function checking for pattern match is very slow. It is written using LINQ. Simple replacement of this LINQ expression with loop makes really huge difference. What is it? Is LINQ really such a bad thing and works so slow or I misunderstand something?</p> <pre><code>private static bool PatternMatch1(byte[] buffer, int position, string pattern) { int i = 0; foreach (char c in pattern) { if (buffer[position + i++] != c) { return false; } } return true; } </code></pre> <p>version 2 with LINQ (suggested by Resharper)</p> <pre><code>private static bool PatternMatch2(byte[] buffer, int position, string pattern) { int i = 0; return pattern.All(c =&gt; buffer[position + i++] == c); } </code></pre> <p>version 3 with LINQ</p> <pre><code>private static bool PatternMatch3(byte[] buffer, int position, string pattern) { return !pattern.Where((t, i) =&gt; buffer[position + i] != t).Any(); } </code></pre> <p>version 4 using lambda</p> <pre><code>private static bool PatternMatch4(byte[] buffer, int position, string pattern, Func&lt;char, byte, bool&gt; predicate) { int i = 0; foreach (char c in pattern) { if (predicate(c, buffer[position + i++])) { return false; } } return true; } </code></pre> <p>and here is the usage with large buffer</p> <pre><code>const int SIZE = 1024 * 1024 * 50; byte[] buffer = new byte[SIZE]; for (int i = 0; i &lt; SIZE - 3; ++i) { if (PatternMatch1(buffer, i, "xxx")) { Console.WriteLine(i); } } </code></pre> <p>Calling <code>PatternMatch2</code> or <code>PatternMatch3</code> is phenomenally slow. It takes about 8 seconds for <code>PatternMatch3</code> and about 4 seconds for <code>PatternMatch2</code>, while calling <code>PatternMatch1</code> takes about 0.6. As far as I understand it is the same code and I see no difference. Any ideas?</p>
    singulars
    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