I have a bool array
private bool[] example = {false, false};
And I change them using a function which also returns true if both values are true.
private bool checkExample(bool firstCondition, bool secondCondition){
example = new bool[]{firstCondition, secondCondition};
return example.All(x => x);
}
I am worried about the memory here. Is it safe changing the array by allocating a new array? new bool[]{firstCondition, secondCondition};
What really happens under the hood? From my understanding, since it's inside a function, we're using short term storage? Or because we're using the keyword new we're using long term storage?
I highly value your help.
Example use case:
checkExample(example[0], true); // and vice versa
CodePudding user response:
What's happening here is quite simple. First you need to realize that all arrays (even arrays of a value type (like bool) are instances of a reference type. So, when you say:
private bool[] example = {false, false};
what you are doing is creating a field in your class that contains a reference to a singly dimensioned array of bool. Since you are initializing it, the array is created and initialized, creating an object on the managed heap.
In your method, you are then doing this:
example = new bool[]{firstCondition, secondCondition};
In that code, you are referring to the that same example member as you initialized. What happens in that code is that a new array of bool is created on the managed heap and initialized, and you are assigning to the example field a reference to that new array.
At that point, unless you assigned a reference to that original array to something else (a long-lived variable, a field or a property), the original array no longer has any references to it. Once an object on the managed heap no longer has any references to it, it becomes eligible for garbage collection.
At some point in the future, the garbage collector will come by and "collect" the memory. If the array hadn't been around very long, then it will be collected in a Gen0 collection (which is pretty cheap). In all likelihood, it will be collected in a Gen1 or Gen2 collection (each of which costs more).
In general, you shouldn't need to worry about things like this. A managed (/garbage collected) system expects that your code will produce garbage. Allocation in .NET is very cheap. Lots of effort goes into making garbage collection (particularly of small objects) efficient.
CodePudding user response:
Why don't use this, if you don't need to create a new array for some another reasons
private bool checkExample(bool firstCondition, bool secondCondition){
example[0]=firstCondition;
example[1]= secondCondition;
return example.All(x => x);
}
