Note that there are some explanatory texts on larger screens.

plurals
  1. POwhy unsafe block with pointers is slower than regular version
    text
    copied!<p>I am testing using unsafe and pointers on character match counting a 200 byte array along every position in a 1 meg long char array as an experiment with safe/unsafe/dll call speed comparison.</p> <p>They are run in release mode with optimize code on, allow unsafe, no bounds checking. Long char array is used purposely used to minimize calling overhead impacts.</p> <p>The times i get are</p> <blockquote> <p>regular 560 ms</p> <p>unsafe 830 ms</p> <p>dll 205 ms</p> </blockquote> <p>why is the unsafe slower??</p> <pre><code> byte[] buffer = new Byte[1000000]; byte[] check = new Byte[1000]; [DllImport("sortitdev.dll", CallingConvention=CallingConvention.StdCall)] //[DllImport("sortitfast.dll", CallingConvention=CallingConvention.StdCall)] //[DllImport("sortitpellas.dll", CallingConvention=CallingConvention.StdCall)] public unsafe static extern void sortitt([MarshalAs(UnmanagedType.LPArray)] byte[] buffer); public MainForm() { InitializeComponent(); } void Button1Click(object sender, EventArgs e) // do char array matching { byte match; Random rnd = new Random(); for(int i=0;i&lt;1000000;i++) buffer[i]=(byte)rnd.Next(0,256); for(int i=0;i&lt;200;i++) check[i]=(byte)rnd.Next(0,256); Stopwatch sw = Stopwatch.StartNew(); int kk=0; int jq=0; while(kk&lt;999000) { kk++; match=0; for(jq=0;jq&lt;199;jq++) if(buffer[kk+jq]==check[jq])match++; buffer[kk]=match; } sw.Stop(); textBox1.Text= sw.Elapsed.TotalMilliseconds.ToString(); sw.Reset(); sw.Start(); unsafe { fixed (byte* bufptr=&amp;buffer[0] , chckptr=&amp;check[0]) { byte* bufptrC=bufptr; // modifiable pointer byte* chckptrC=chckptr; byte* bufhldptr; byte* chckhldptr; int k=999000; int jw=0; while(k&gt;0) { bufhldptr=bufptrC; match=0; chckhldptr=chckptrC; for(jw=0;jw&lt;199;jw++) if(*bufhldptr++==*chckhldptr++)match++; *bufptrC++=match; k--; } } sw.Stop(); textBox2.Text= sw.Elapsed.TotalMilliseconds.ToString(); } sw.Reset(); for(int tt=0;tt&lt;200;tt++) buffer[tt]=(byte)tt; sw.Start(); unsafe { fixed(byte* dadata=&amp;buffer[0]) { sortitt(buffer); } } sw.Stop(); textBox3.Text= sw.Elapsed.TotalMilliseconds.ToString(); int kll=(int)buffer[1]; textBox4.Text= kll.ToString(); } } </code></pre>
 

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