问题
If you look for the DBBool implementation in C#, few overloaded operators (logical operators |
, &
, !
) new while returning. I believe that is not necessary and a small waste of memory. DBBool is a struct and a copy is made when it's passed into a method so there is no reason for that.
// Logical negation operator. Returns True if the operand is False, Null
// if the operand is Null, or False if the operand is True.
public static DBBool operator !(DBBool x)
{
return new DBBool(-x.value);
}
// Logical AND operator. Returns False if either operand is False,
// Null if either operand is Null, otherwise True.
public static DBBool operator &(DBBool x, DBBool y)
{
return new DBBool(x.value < y.value ? x.value : y.value);
}
// Logical OR operator. Returns True if either operand is True,
// Null if either operand is Null, otherwise False.
public static DBBool operator |(DBBool x, DBBool y)
{
return new DBBool(x.value > y.value ? x.value : y.value);
}
It should be this way without newing.
public static DBBool operator !(DBBool x)
{
if (x.value > 0) return False;
if (x.value < 0) return True;
return Null;
}
public static DBBool operator &(DBBool x, DBBool y)
{
return x.value < y.value ? x : y;
}
public static DBBool operator |(DBBool x, DBBool y)
{
return x.value > y.value ? x : y;
}
回答1:
- it is a struct, so "new" really means "initialize a value on the stack" - this is cheap and is not the same as a new object
- most structs are immutable; I'm guessing this is too; hence it can't just mutate the parameter value and return that - it must initialize a new value with the desired contents
来源:https://stackoverflow.com/questions/12082201/why-new-while-returning-for-overloaded-operators-for-dbbool-tristate-implement