[quoted text, click to view] "Goran Sliskovic" <gsliskov@yahoo.com> wrote in message
news:%23T1hCCyXGHA.4248@TK2MSFTNGP05.phx.gbl...
>
> "Zeeshan Gulzar" <ZeeshanGulzar@discussions.microsoft.com> wrote in
> message
> news:9655BAA0-7828-440A-BEB7-1FFD53A40034@microsoft.com...
> ...
>> A method is called at every mouse move or says method calls frequently.
>> The method is like this
>>
>> public void form_mouseup(object sender, EventArgs e)
>> {
>> int x = y * 12; //Here y is a member variable(int), defined at class
>> scope
>> // Process the variable x here
>> }
>>
>> Variable x is initialized at every call in the above code. Although it is
>> created at stack but take some time and suppose x is a user-defined
>> struct
>> with size of 120 Bytes. Is it best practice Or the following equivalent
> code.
>>
If x is 120 bytes, it's likely that computing the values within takes a lot
more time than allocating the space. How often is x used? How often does y
change?
Make sure y is a property, not a field. Make a member field "private
Nullable<type x is> cachedx". The setter for y nulls cachedx. Your
function starts with the line:
sometype x = cachedx?? CacheX();
Then write a method CacheX() which creates a new object computed from the
value of y, saves a reference in cachedx and also returns it. CacheX()
shouldn't have side effects because it might not be called exactly once
every time y changes (less than once if y changes often, more than once if
multi-threading), nor every time x is used. Also, CacheX() should return
the object it created, not cachedx, because another thread could set cachedx
back to null meanwhile.
If x is used 10,000 times for each change to y, then you can get rid of the
test for null by caching x immediately when y changes (i.e. y's getter does
CacheX() instead of cachedx = null).
[quoted text, click to view] >> public void form_mouseup(object sender, EventArgs e)
>> {
>> x = y * 12; //Here y is a member variable(int), defined at class
> scope
>> // Also x is also defined at class scope
>> // Process the variable x here
>> }
>>
> ...
>
> Hi,
>
> Before you start such optimization, measure the performance impact by
> profiler first. Also, I suspect it is same time needed to allocate stack
> for
> 1 variable as for 1000, regardles of size. That would of course depend of
> implementation. Usually, allocation on stack is only adding/substracting
> stack pointer. It can be done once per every block regardless of number of
> variables allocated.
>
> Regards,
> Goran
>
>