Reputation: 47
I was looking at someone else's code and wondering why anyone would do it and what sort of implications it would have in C#. I've seen some information on other languages or for similar scenarios but not this specific scenario.
This is in a web service business rule.
public class MyClass
{
StringBuilder strBuild = new StringBuilder();
SQLText sqlQry = new SQLText();
...
public myMethod1()
{
strBuild = new StringBuilder();
sqlQry = new SQLText();
...
}
private myMethod2()
{
strBuild = new StringBuilder();
sqlQry = new SQLText();
...
}
...
}
If I was writing this I would not create class variables and would simply create local variables for the StringBuilder and SQLText types in each method I needed them. The above seems to be poor programming because it essentially creates a global variable that one has to remember to instantiate in each method or re-instantiate (to "clear" it).
But does the code above do any real harm?
How does the garbage collector handle this? If the class variable is instantiated 30 times in different methods will it lose track of the initial declarations and fail to free the memory or would it still eventually get cleared?
What about performance? Is it faster to use the same class variable(s) like this in a bunch of different methods or create a local variable in the respective methods?
Upvotes: 0
Views: 728
Reputation: 1502106
But does the code above do any real harm?
Yes - it fouls up the state of the class. It looks like this class shouldn't really have any state - these should be local variables. However, to the casual observer this appears to be real state associated with the object.
1) How does the garbage collector handle this? If the class variable is instantiated 30 times in different methods will it lose track of the initial declarations and fail to free the memory or would it still eventually get cleared?
Instance variables aren't "instantiated" - they're just assigned. And once the previous value has been overwritten, if nothing else refers to the object which the old value referred to, that object will be eligible for garbage collection. No harm there.
2) What about performance? Is it faster to use the same class variable(s) like this in a bunch of different methods or create a local variable in the respective methods?
I would expect local variables to behave slightly faster, if anything - but any performance difference is almost certainly going to be entirely insignificant (probably unmeasurably so), and shouldn't be used to decide what to do.
Just change them to local variables - clean up the design.
Upvotes: 3