Note that there are some explanatory texts on larger screens.

plurals
  1. POMemory management - should I worry about resizing a temporary array of long-lived objects within a state machine?
    primarykey
    data
    text
    <p>Garbage collection in .NET leads many to believe that lightweight objects can be treated as temporary. This seems especially true of arrays that hold object references to objects that are instantiated outside of the context of the array initialization. </p> <p>Consequently, it would seem that it should not really matter if a new array is initialized within an iteration of a state machine, particularly if that state blocks in any fashion, such as with a call to <code>WaitHandle.WaitAny()</code>.</p> <p>I would much rather create a new array as a lightweight container on-the-fly to hold my WaitHandle objects, than to resize the <code>WaitHandle[]</code> array using <code>Array.Resize&lt;T&gt;()</code>. </p> <p>Why? Well, assuming that memory is cheap and that <code>Array.Resize&lt;T&gt;()</code> will have to perform a memory allocation or a memory copy of some sort anyhow, it seems more efficient to simply implicitly discard the array by passing in a new one every time into the static method like this: </p> <pre><code>// using C# 3.0 array initialization syntax eventIndex = WaitHandle.WaitAny(new[] { _stateStopEvent }, 5000); </code></pre> <p>(Check out this <a href="http://kozmic.pl/archive/2008/02/22/c-tricks-array-initialization-in-c-3.0.aspx" rel="nofollow noreferrer">link</a> for details on the array syntax)</p> <p><code>_stateStopEvent</code> is one of several potential events that may apply to any or all states, and those ManualResetEvent objects are declared at a higher scope, so it seems that managing the array is actually more work than it's worth. </p> <p>Furthermore, if the code is declaring a temporary reference variable for the array and simply assigning a new array instance to it within each iteration of the state machine, what's the difference, from a performance perspective? Why not simply skip that step as shown in the code snippet above? </p> <p>Is resizing the <code>WaitHandle[]</code> array by using <code>Array.Resize&lt;T&gt;()</code>, a better approach? </p> <p>Taking byte[] arrays out of the picture, if I need to resize an array, wouldn't I just use a List or a Dictionary instance as is recommended <a href="https://stackoverflow.com/questions/434761/array-versus-listt-when-to-use-which">here</a>?</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