Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should variables be reused to optimize resource utilization?

I am Using Microsoft Visual C# 2010. I have several methods that use a large bitmap for local processing, and each method can be called several times.
I can declare a global variable and reuse it:

Bitmap workPic, editPic;
...
void Method1() {
    workPic = new Bitmap(editPic);
    ...
}
void Method2() {
    workPic = new Bitmap(editPic.Width * 2, editPic.Height * 2);
    ...
}

or declare a local variable in each method:

Bitmap editPic;
...
void Method1() {
    Bitmap workPic = new Bitmap(editPic);
    ...
}
void Method2() {
    Bitmap workPic = new Bitmap(editPic.Width * 2, editPic.Height * 2);
    ...
}

The second way is better for code clarity (local variables for local use). Is there a difference in terms of resource utilization?

like image 397
Paulo Barretto Avatar asked Nov 05 '15 12:11

Paulo Barretto


People also ask

What is necessary for Utilisation of resources?

Generally, the utilisation of resources depends upon various factors, such as: Availability of resources • Skill of human beings • Availability of capital • Availability of water • Advancement of technology (tools, machines, etc.) Availability of transport and communication facilities, etc.

What is the technique of proper Utilisation of resources called?

Resource planning refers to the strategy for planned and judicious utilisation of resources. Resource planning is essential for the sustainable existence of all forms of life.

What measures can we use for assessing resource utilization?

While there are multiple ways to measure resource utilization, the simplest and most common method is by taking the actual number of hours worked by a resource, and dividing it by the total number of hours that the resource could have worked.


1 Answers

If you intend to keep the memory allocated to you can use workPic again after the method, you should register it as class variable. If not, you can free memory (always a good idea) by letting it go out of scope.

Allocating one variable doesn't matter much to the framework which manages memory. Only if you recreate a variable inside a tight loop you may benefit by reusing the variable. If you have basic types, you even reuse the same memory. Else, only the reference to the allocated memory is kept, so not that much benefit you have from there.

Note it is very important to Dispose your workPic since now you have a memory leak in the unmanaged memory behind Bitmap. Preferably use using.

like image 144
Patrick Hofman Avatar answered Nov 14 '22 22:11

Patrick Hofman