I'm sure it is negligible, but given that I want to assign true
to a boolean field from within a method, does this choice make any difference? If so, why?
field = true; // could already be true, but I don't care
versus
if(!field) field = true;
To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false. Boolean values are not actually stored in Boolean variables as the words “true” or “false”.
An alternative approach is to use the logical OR (||) operator. To check if a value is of boolean type, check if the value is equal to false or equal to true , e.g. if (variable === true || variable === false) . Boolean values can only be true and false , so if either condition is met, the value has a type of boolean.
The default value of Boolean is False . Boolean values are not stored as numbers, and the stored values are not intended to be equivalent to numbers. You should never write code that relies on equivalent numeric values for True and False .
If you want to define a boolean in Python, you can simply assign a True or False value or even an expression that ultimately evaluates to one of these values. You can check the type of the variable by using the built-in type function in Python.
I'd say no. But this does depend on the fact that we really are talking about a field as opposed to a property, which may (though it definitely should not) exhibit different behavior in the two snippets you included (i.e., if there is logic with side effects in the getter).
Update: If you're talking about performance overhead, there is practically no difference—but I believe assignment is ever-so-slightly less expensive (than reading the value). Here is a sample program to demonstrate this:
bool b = false;
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < int.MaxValue; ++i)
{
b = true;
}
sw.Stop();
TimeSpan setNoCheckTime = sw.Elapsed;
sw = Stopwatch.StartNew();
for (int i = 0; i < int.MaxValue; ++i)
{
// This part will never assign, as b will always be true.
if (!b)
{
b = true;
}
}
sw.Stop();
TimeSpan checkSetTime = sw.Elapsed;
Console.WriteLine("Assignment: {0} ms", setNoCheckTime.TotalMilliseconds);
Console.WriteLine("Read: {0} ms", checkSetTime.TotalMilliseconds);
Output on my machine:
Assignment: 2749.6285 ms Read: 4543.0343 ms
For a field, just set it. For a property, it could be more complex, depending on whether the get
or set
is disproportionately expensive, and/or whether the set
checks this internally (bypassing events etc).
As a general rule for properties, just set it, until you know this to be an issue due to profiling.
For fields; don't worry excessively about it; default to just set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With