Note that there are some explanatory texts on larger screens.

plurals
  1. POCan this code be optimised?
    primarykey
    data
    text
    <p>I have some image processing code that loops through 2 multi-dimensional byte arrays (of the same size). It takes a value from the source array, performs a calculation on it and then stores the result in another array.</p> <pre><code>int xSize = ResultImageData.GetLength(0); int ySize = ResultImageData.GetLength(1); for (int x = 0; x &lt; xSize; x++) { for (int y = 0; y &lt; ySize; y++) { ResultImageData[x, y] = (byte)((CurrentImageData[x, y] * AlphaValue) + (AlphaImageData[x, y] * OneMinusAlphaValue)); } } </code></pre> <p>The loop currently takes ~11ms, which I assume is mostly due to accessing the byte arrays values as the calculation is pretty simple (2 multiplications and 1 addition).</p> <p>Is there anything I can do to speed this up? It is a time critical part of my program and this code gets called 80-100 times per second, so any speed gains, however small will make a difference. Also at the moment xSize = 768 and ySize = 576, but this will increase in the future.</p> <p><strong>Update</strong>: Thanks to <a href="https://stackoverflow.com/users/69083/guffa">Guffa</a> (see answer below), the following code saves me 4-5ms per loop. Although it is <em>unsafe</em> code.</p> <pre><code>int size = ResultImageData.Length; int counter = 0; unsafe { fixed (byte* r = ResultImageData, c = CurrentImageData, a = AlphaImageData) { while (size &gt; 0) { *(r + counter) = (byte)(*(c + counter) * AlphaValue + *(a + counter) * OneMinusAlphaValue); counter++; size--; } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    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