Check for equality before assigning?
Is it a good practice to assign a value only if it's not equal to the assignee? For example, would:
bool isVisible = false;
if(TextBox1.Visibl开发者_Go百科e != isVisible)
TextBox1.Visible = isVisible;
be more desirable than:
bool isVisible = false;
TextBox1.Visible = isVisible;
Furthermore, does the answer depend on the data type, like an object with a costlier Equals method versus an object with a costlier assignment method?
From a readability standpoint, I'd definitely prefer the second way -- just assign the darn thing.
Some object properties have semantics that require that assigning a value the property already holds will have a particular effect. For example, setting an object's "text" may force a redraw, even if the value doesn't change. When dealing with such objects, unless one wants to force the action to take place, one should often test and set if unequal.
Generally, with fields, there is no advantage to doing a comparison before a set. There is one notable exception, however: if many concurrently-running threads will be wanting to set a field to the same value, and it's likely to already hold that value, caching behavior may be very bad if all the threads are unconditionally writing to that field, since a processor that wants to write to it will have to acquire the cache line from the most recent processor that wrote it. By contrast, if all the processors are simply reading the field and deciding to leave it alone, they can all share the cache line, resulting in much better performance.
Your instincts seem about right - it depends on the cost of the operations.
In your example, making a text box visible or invisible, the cost of the test is imperceptible (just check a bit in the window structure) and the cost of assignment is also typically imperceptible (repaint the window). In fact, if you set the "visible" bit to its existing value you'll still incur the function call cost, but the window manager will check the bit and return immediately. In this case, just go ahead and assign it.
But in other cases it might matter. For example, if you have a cached copy of a long string or binary object, and whenever you assign a new value it gets saved back to a database. Then you might find that the cost of testing for equality every time is worth it to save unnecessary writes to the database. No doubt you can imagine more expensive scenarios.
So in the general case you've got at least these primary variables to consider: the cost of the test, the cost of the assignment, and the relative frequencies of assigning a new value versus assigning the same value.
精彩评论