Redundant comparison & “if” before assignment
Here is the example:
if(value != ageValue) {
ageValue = value;
}
I mean, if we assign the value of a variable to another one, why would we need to check if they have anyway the same value?
That confuses me. Here is the broader context:
private double ageValue;
public double Age {
get {
return ageValue;
}
set {
if(value != ageValue) {
ageValue = value;
}
}
}
c# .net if-statement
New contributor
TheOrlexx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
|
show 13 more comments
Here is the example:
if(value != ageValue) {
ageValue = value;
}
I mean, if we assign the value of a variable to another one, why would we need to check if they have anyway the same value?
That confuses me. Here is the broader context:
private double ageValue;
public double Age {
get {
return ageValue;
}
set {
if(value != ageValue) {
ageValue = value;
}
}
}
c# .net if-statement
New contributor
TheOrlexx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
14
assuming ageValue isn't a property, but is only a variable then there is no point. If ageValue is a property, maybe something happens in the set?
– Alex Anderson
10 hours ago
2
Without greater context (isageValuebound to a display field? IsageValuea property?), this question has only answers that are not very helpful.
– crashmstr
10 hours ago
8
So you only set the ageValue when the value is something new. Right here it doesn't make sense to have anifbut in other cases when we do more than just set the value it can save time. For example, in a WPF MVVM application afterageValue = valuewe'd most likely callNotifyPropertyChangedso the GUI knows that a property changed, but we'd only want to do this if our property actually changed
– MindSwipe
10 hours ago
4
With regard to your added/edited code: yes, theifis redundant in this particular code example you have given.
– elgonzo
10 hours ago
2
Related: Is it a sensible optimization to check whether a variable holds a specific value before writing that value?
– GSerg
7 hours ago
|
show 13 more comments
Here is the example:
if(value != ageValue) {
ageValue = value;
}
I mean, if we assign the value of a variable to another one, why would we need to check if they have anyway the same value?
That confuses me. Here is the broader context:
private double ageValue;
public double Age {
get {
return ageValue;
}
set {
if(value != ageValue) {
ageValue = value;
}
}
}
c# .net if-statement
New contributor
TheOrlexx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Here is the example:
if(value != ageValue) {
ageValue = value;
}
I mean, if we assign the value of a variable to another one, why would we need to check if they have anyway the same value?
That confuses me. Here is the broader context:
private double ageValue;
public double Age {
get {
return ageValue;
}
set {
if(value != ageValue) {
ageValue = value;
}
}
}
c# .net if-statement
c# .net if-statement
New contributor
TheOrlexx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
TheOrlexx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited 3 hours ago
Solomon Ucko
7752822
7752822
New contributor
TheOrlexx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
asked 10 hours ago
TheOrlexxTheOrlexx
13327
13327
New contributor
TheOrlexx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
TheOrlexx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
TheOrlexx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
14
assuming ageValue isn't a property, but is only a variable then there is no point. If ageValue is a property, maybe something happens in the set?
– Alex Anderson
10 hours ago
2
Without greater context (isageValuebound to a display field? IsageValuea property?), this question has only answers that are not very helpful.
– crashmstr
10 hours ago
8
So you only set the ageValue when the value is something new. Right here it doesn't make sense to have anifbut in other cases when we do more than just set the value it can save time. For example, in a WPF MVVM application afterageValue = valuewe'd most likely callNotifyPropertyChangedso the GUI knows that a property changed, but we'd only want to do this if our property actually changed
– MindSwipe
10 hours ago
4
With regard to your added/edited code: yes, theifis redundant in this particular code example you have given.
– elgonzo
10 hours ago
2
Related: Is it a sensible optimization to check whether a variable holds a specific value before writing that value?
– GSerg
7 hours ago
|
show 13 more comments
14
assuming ageValue isn't a property, but is only a variable then there is no point. If ageValue is a property, maybe something happens in the set?
– Alex Anderson
10 hours ago
2
Without greater context (isageValuebound to a display field? IsageValuea property?), this question has only answers that are not very helpful.
– crashmstr
10 hours ago
8
So you only set the ageValue when the value is something new. Right here it doesn't make sense to have anifbut in other cases when we do more than just set the value it can save time. For example, in a WPF MVVM application afterageValue = valuewe'd most likely callNotifyPropertyChangedso the GUI knows that a property changed, but we'd only want to do this if our property actually changed
– MindSwipe
10 hours ago
4
With regard to your added/edited code: yes, theifis redundant in this particular code example you have given.
– elgonzo
10 hours ago
2
Related: Is it a sensible optimization to check whether a variable holds a specific value before writing that value?
– GSerg
7 hours ago
14
14
assuming ageValue isn't a property, but is only a variable then there is no point. If ageValue is a property, maybe something happens in the set?
– Alex Anderson
10 hours ago
assuming ageValue isn't a property, but is only a variable then there is no point. If ageValue is a property, maybe something happens in the set?
– Alex Anderson
10 hours ago
2
2
Without greater context (is
ageValue bound to a display field? Is ageValue a property?), this question has only answers that are not very helpful.– crashmstr
10 hours ago
Without greater context (is
ageValue bound to a display field? Is ageValue a property?), this question has only answers that are not very helpful.– crashmstr
10 hours ago
8
8
So you only set the ageValue when the value is something new. Right here it doesn't make sense to have an
if but in other cases when we do more than just set the value it can save time. For example, in a WPF MVVM application after ageValue = value we'd most likely call NotifyPropertyChanged so the GUI knows that a property changed, but we'd only want to do this if our property actually changed– MindSwipe
10 hours ago
So you only set the ageValue when the value is something new. Right here it doesn't make sense to have an
if but in other cases when we do more than just set the value it can save time. For example, in a WPF MVVM application after ageValue = value we'd most likely call NotifyPropertyChanged so the GUI knows that a property changed, but we'd only want to do this if our property actually changed– MindSwipe
10 hours ago
4
4
With regard to your added/edited code: yes, the
if is redundant in this particular code example you have given.– elgonzo
10 hours ago
With regard to your added/edited code: yes, the
if is redundant in this particular code example you have given.– elgonzo
10 hours ago
2
2
Related: Is it a sensible optimization to check whether a variable holds a specific value before writing that value?
– GSerg
7 hours ago
Related: Is it a sensible optimization to check whether a variable holds a specific value before writing that value?
– GSerg
7 hours ago
|
show 13 more comments
5 Answers
5
active
oldest
votes
Here is a code sample when the check is quite useful:
public class MyClass {
...
int ageValue = 0;
public int AgeValue {
get {
return ageValue
}
protected set {
... // value validation here
// your code starts
if (value != ageValue) {
ageValue = value;
}
// your code ends
else
return; // do nothing since value == ageValue
// ageValue has been changed
// Time (or / and memory) consuming process
SaveToRDBMS();
InvalidateCache();
...
}
}
...
More natural implementation, however, is to check in the very beginning in order to avoid unnecessary computation.
protected set {
if (ageValue == value)
return;
... // value validation here
ageValue = value;
// ageValue has been changed
// Time (or / and memory) consuming process
SaveToRDBMS();
InvalidateCache();
...
}
1
True, however I don't believe that a "time (or / and memory) consuming process" is a good thing to do in the setter. After all, this is why we can't useasync/awaiton properties. See the answer of this question..
– Guilherme
5 hours ago
Personally I'd have the check beif (value == ageValue) return;
– mowwwalker
4 hours ago
add a comment |
In a winforms control we had set the BackgroundColor to a specific color:
myControl.BackgroundColor = Color.White
Under specific circumstances this could happen in a tight loop and lead to a frozen UI. After some performance analysis we found that this call was the reason for the frozen UI and so we simply changed it to:
if (myControl.BackgroundColor != Color.White)
myControl.BackgroundColor = Color.White
And the performance of our tool was back on track (and then we eliminated the reason of the tight loop).
So this check is not always redundant. Especially if the target is a property which does more within the setter then simply applying the value to a backing store.
add a comment |
The if is, on inspection, not redundant. It depends on the remaining implementation. Note that in C#, != can be overloaded, which means that evaluation can have side effects. Futhermore, the checked variables could be implemented as properties, which also can have side effects on evaluation.
17
And if you find != has been overloaded, or someone has implemented properties with grossly unintuitive side effects, immediately draw and quarter the responsible developer.
– BobbyA
10 hours ago
add a comment |
This question has gained quite some comments but so far all answers try to reframe the question to address issues with operator overloading or side effects of the setter.
If the setter is using by multiple threads it can really make a difference. The check before set pattern can (you should measure) be useful if you are iterating over the same data with multiple threads which alter the data. The text book name for this phenomena is called false sharing. If you read the data and did verify that it already matches the target value you can omit the write.
If you omit the write the CPU does not need to flush the cache line (a 64 byte block on Intel CPUs) to ensure that other cores see the changed value. If the other core was about to read some other data from that 64 byte block then you just have slowed down your core and increased cross core traffic to synchronize memory contents between CPU caches.
The following sample application shows this effect which also contains the check before write condition:
if (tmp1 != checkValue) // set only if not equal to checkvalue
{
values[i] = checkValue;
}
Here is the full code:
class Program
{
static void Main(string args)
{
SetArray(1, 10);
SetArray(2, 10);
}
private static void SetArray(int checkValue, int nTimes)
{
const int N = 500_000_000;
int values = new int[N]; // 4 GB
for (int k = 0; k < nTimes; k++) // set array values to 1
{
for (int i = 0; i < values.Length; i++)
{
values[i] = 1;
}
var sw = Stopwatch.StartNew();
Action acc = () =>
{
int tmp1 = 0;
for (int i = 0; i < values.Length; i++)
{
tmp1 = values[i];
if (tmp1 != checkValue) // set only if not equal to checkvalue
{
values[i] = checkValue;
}
}
};
Parallel.Invoke(acc, acc, acc); // Let this run on 3 cores
sw.Stop();
Console.WriteLine($"Set {N * 4 / (1_000_000_000.0f):F1} GB of Memory in {sw.Elapsed.TotalMilliseconds:F0} ms. Initial Value 1. Set Value {checkValue}");
}
}
}
If you let that run you get values like:
// Value not set
Set 2.0 GB of Memory in 439 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 420 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 429 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 393 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 404 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 395 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 419 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 421 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 442 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 422 ms. Initial Value 1. Set Value 1
// Value written
Set 2.0 GB of Memory in 519 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 582 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 543 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 484 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 523 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 540 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 552 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 527 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 535 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 581 ms. Initial Value 1. Set Value 2
That results in a 22% faster performance which can be significant in high performance number crunching scenarios.
To answer the question as it was written:
You can remove the if statement if access to the memory is only single threaded. If multiple threads are working on the same or nearby data false sharing can happen which can cost you up to ca. 20% of memory access performance.
1
If the setter is used by multiple threads without any synchronization that essentially means the produced data are inconsitent, and at this point the processing speed isn't really that important. C# doesn't require writes to non-volatile fields in one thread to be visible in other threads until a volatile field referenced, or alocktaken/released, or a thread created/terminated.
– Joker_vD
8 hours ago
That is a simplified example. Suppose you have a struct with two fields int F1, F2. And you update them in two threads where one updates only F1 and the other F2. There is no overlap in the written data but your performance will be down due to false sharing. That is meant with false sharing. You have a false data dependency due to how caches of the CPU work.
– Alois Kraus
7 hours ago
2
@Joker_vD: If different threads were writing meaningfully-different data, that would be true. False sharing can occur, however, in cases where all threads that would modify something would store the same value or equivalent values. For example, if an object has a field to say whether it has ever done something, setting the flag totruewhen it already is may degrade the performance of other threads trying to read the flag.
– supercat
6 hours ago
add a comment |
Yes, this if is useless. You check if the value are the same (and set it if not).
When the !=-operator is not overloaded, then is this:
private double ageValue;
public double Age
{
get { return ageValue; }
set
{
if (value != ageValue)
{
ageValue = value;
}
}
}
same to
private double ageValue;
public double Age
{
get { return ageValue; }
set { ageValue = value; }
}
Is it useless if the they are properties with getters and setters that perform other operations?
– Amy
10 hours ago
Its the setter-method (look at the question). There can not be any other actions. The only thing (but happend not often out there) is a overloaded!=-operator.
– user6537157
10 hours ago
Yes, the question was expanded with additional context.
– Amy
10 hours ago
Why is the only answer that addresses OP's actual question rather than a "what if" so heavily downvoted?
– helrich
10 hours ago
Because before revision 4 of the question, this answer was wrong. Codor's answer was the only one that was correct.
– Amy
10 hours ago
|
show 3 more comments
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
TheOrlexx is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55300081%2fredundant-comparison-if-before-assignment%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
Here is a code sample when the check is quite useful:
public class MyClass {
...
int ageValue = 0;
public int AgeValue {
get {
return ageValue
}
protected set {
... // value validation here
// your code starts
if (value != ageValue) {
ageValue = value;
}
// your code ends
else
return; // do nothing since value == ageValue
// ageValue has been changed
// Time (or / and memory) consuming process
SaveToRDBMS();
InvalidateCache();
...
}
}
...
More natural implementation, however, is to check in the very beginning in order to avoid unnecessary computation.
protected set {
if (ageValue == value)
return;
... // value validation here
ageValue = value;
// ageValue has been changed
// Time (or / and memory) consuming process
SaveToRDBMS();
InvalidateCache();
...
}
1
True, however I don't believe that a "time (or / and memory) consuming process" is a good thing to do in the setter. After all, this is why we can't useasync/awaiton properties. See the answer of this question..
– Guilherme
5 hours ago
Personally I'd have the check beif (value == ageValue) return;
– mowwwalker
4 hours ago
add a comment |
Here is a code sample when the check is quite useful:
public class MyClass {
...
int ageValue = 0;
public int AgeValue {
get {
return ageValue
}
protected set {
... // value validation here
// your code starts
if (value != ageValue) {
ageValue = value;
}
// your code ends
else
return; // do nothing since value == ageValue
// ageValue has been changed
// Time (or / and memory) consuming process
SaveToRDBMS();
InvalidateCache();
...
}
}
...
More natural implementation, however, is to check in the very beginning in order to avoid unnecessary computation.
protected set {
if (ageValue == value)
return;
... // value validation here
ageValue = value;
// ageValue has been changed
// Time (or / and memory) consuming process
SaveToRDBMS();
InvalidateCache();
...
}
1
True, however I don't believe that a "time (or / and memory) consuming process" is a good thing to do in the setter. After all, this is why we can't useasync/awaiton properties. See the answer of this question..
– Guilherme
5 hours ago
Personally I'd have the check beif (value == ageValue) return;
– mowwwalker
4 hours ago
add a comment |
Here is a code sample when the check is quite useful:
public class MyClass {
...
int ageValue = 0;
public int AgeValue {
get {
return ageValue
}
protected set {
... // value validation here
// your code starts
if (value != ageValue) {
ageValue = value;
}
// your code ends
else
return; // do nothing since value == ageValue
// ageValue has been changed
// Time (or / and memory) consuming process
SaveToRDBMS();
InvalidateCache();
...
}
}
...
More natural implementation, however, is to check in the very beginning in order to avoid unnecessary computation.
protected set {
if (ageValue == value)
return;
... // value validation here
ageValue = value;
// ageValue has been changed
// Time (or / and memory) consuming process
SaveToRDBMS();
InvalidateCache();
...
}
Here is a code sample when the check is quite useful:
public class MyClass {
...
int ageValue = 0;
public int AgeValue {
get {
return ageValue
}
protected set {
... // value validation here
// your code starts
if (value != ageValue) {
ageValue = value;
}
// your code ends
else
return; // do nothing since value == ageValue
// ageValue has been changed
// Time (or / and memory) consuming process
SaveToRDBMS();
InvalidateCache();
...
}
}
...
More natural implementation, however, is to check in the very beginning in order to avoid unnecessary computation.
protected set {
if (ageValue == value)
return;
... // value validation here
ageValue = value;
// ageValue has been changed
// Time (or / and memory) consuming process
SaveToRDBMS();
InvalidateCache();
...
}
edited 2 hours ago
Keaton Thomas
111
111
answered 10 hours ago
Dmitry BychenkoDmitry Bychenko
111k1097138
111k1097138
1
True, however I don't believe that a "time (or / and memory) consuming process" is a good thing to do in the setter. After all, this is why we can't useasync/awaiton properties. See the answer of this question..
– Guilherme
5 hours ago
Personally I'd have the check beif (value == ageValue) return;
– mowwwalker
4 hours ago
add a comment |
1
True, however I don't believe that a "time (or / and memory) consuming process" is a good thing to do in the setter. After all, this is why we can't useasync/awaiton properties. See the answer of this question..
– Guilherme
5 hours ago
Personally I'd have the check beif (value == ageValue) return;
– mowwwalker
4 hours ago
1
1
True, however I don't believe that a "time (or / and memory) consuming process" is a good thing to do in the setter. After all, this is why we can't use
async/await on properties. See the answer of this question..– Guilherme
5 hours ago
True, however I don't believe that a "time (or / and memory) consuming process" is a good thing to do in the setter. After all, this is why we can't use
async/await on properties. See the answer of this question..– Guilherme
5 hours ago
Personally I'd have the check be
if (value == ageValue) return;– mowwwalker
4 hours ago
Personally I'd have the check be
if (value == ageValue) return;– mowwwalker
4 hours ago
add a comment |
In a winforms control we had set the BackgroundColor to a specific color:
myControl.BackgroundColor = Color.White
Under specific circumstances this could happen in a tight loop and lead to a frozen UI. After some performance analysis we found that this call was the reason for the frozen UI and so we simply changed it to:
if (myControl.BackgroundColor != Color.White)
myControl.BackgroundColor = Color.White
And the performance of our tool was back on track (and then we eliminated the reason of the tight loop).
So this check is not always redundant. Especially if the target is a property which does more within the setter then simply applying the value to a backing store.
add a comment |
In a winforms control we had set the BackgroundColor to a specific color:
myControl.BackgroundColor = Color.White
Under specific circumstances this could happen in a tight loop and lead to a frozen UI. After some performance analysis we found that this call was the reason for the frozen UI and so we simply changed it to:
if (myControl.BackgroundColor != Color.White)
myControl.BackgroundColor = Color.White
And the performance of our tool was back on track (and then we eliminated the reason of the tight loop).
So this check is not always redundant. Especially if the target is a property which does more within the setter then simply applying the value to a backing store.
add a comment |
In a winforms control we had set the BackgroundColor to a specific color:
myControl.BackgroundColor = Color.White
Under specific circumstances this could happen in a tight loop and lead to a frozen UI. After some performance analysis we found that this call was the reason for the frozen UI and so we simply changed it to:
if (myControl.BackgroundColor != Color.White)
myControl.BackgroundColor = Color.White
And the performance of our tool was back on track (and then we eliminated the reason of the tight loop).
So this check is not always redundant. Especially if the target is a property which does more within the setter then simply applying the value to a backing store.
In a winforms control we had set the BackgroundColor to a specific color:
myControl.BackgroundColor = Color.White
Under specific circumstances this could happen in a tight loop and lead to a frozen UI. After some performance analysis we found that this call was the reason for the frozen UI and so we simply changed it to:
if (myControl.BackgroundColor != Color.White)
myControl.BackgroundColor = Color.White
And the performance of our tool was back on track (and then we eliminated the reason of the tight loop).
So this check is not always redundant. Especially if the target is a property which does more within the setter then simply applying the value to a backing store.
edited 5 hours ago
Chris Hayes
8,12832241
8,12832241
answered 10 hours ago
OliverOliver
33.2k771118
33.2k771118
add a comment |
add a comment |
The if is, on inspection, not redundant. It depends on the remaining implementation. Note that in C#, != can be overloaded, which means that evaluation can have side effects. Futhermore, the checked variables could be implemented as properties, which also can have side effects on evaluation.
17
And if you find != has been overloaded, or someone has implemented properties with grossly unintuitive side effects, immediately draw and quarter the responsible developer.
– BobbyA
10 hours ago
add a comment |
The if is, on inspection, not redundant. It depends on the remaining implementation. Note that in C#, != can be overloaded, which means that evaluation can have side effects. Futhermore, the checked variables could be implemented as properties, which also can have side effects on evaluation.
17
And if you find != has been overloaded, or someone has implemented properties with grossly unintuitive side effects, immediately draw and quarter the responsible developer.
– BobbyA
10 hours ago
add a comment |
The if is, on inspection, not redundant. It depends on the remaining implementation. Note that in C#, != can be overloaded, which means that evaluation can have side effects. Futhermore, the checked variables could be implemented as properties, which also can have side effects on evaluation.
The if is, on inspection, not redundant. It depends on the remaining implementation. Note that in C#, != can be overloaded, which means that evaluation can have side effects. Futhermore, the checked variables could be implemented as properties, which also can have side effects on evaluation.
answered 10 hours ago
CodorCodor
15.5k82648
15.5k82648
17
And if you find != has been overloaded, or someone has implemented properties with grossly unintuitive side effects, immediately draw and quarter the responsible developer.
– BobbyA
10 hours ago
add a comment |
17
And if you find != has been overloaded, or someone has implemented properties with grossly unintuitive side effects, immediately draw and quarter the responsible developer.
– BobbyA
10 hours ago
17
17
And if you find != has been overloaded, or someone has implemented properties with grossly unintuitive side effects, immediately draw and quarter the responsible developer.
– BobbyA
10 hours ago
And if you find != has been overloaded, or someone has implemented properties with grossly unintuitive side effects, immediately draw and quarter the responsible developer.
– BobbyA
10 hours ago
add a comment |
This question has gained quite some comments but so far all answers try to reframe the question to address issues with operator overloading or side effects of the setter.
If the setter is using by multiple threads it can really make a difference. The check before set pattern can (you should measure) be useful if you are iterating over the same data with multiple threads which alter the data. The text book name for this phenomena is called false sharing. If you read the data and did verify that it already matches the target value you can omit the write.
If you omit the write the CPU does not need to flush the cache line (a 64 byte block on Intel CPUs) to ensure that other cores see the changed value. If the other core was about to read some other data from that 64 byte block then you just have slowed down your core and increased cross core traffic to synchronize memory contents between CPU caches.
The following sample application shows this effect which also contains the check before write condition:
if (tmp1 != checkValue) // set only if not equal to checkvalue
{
values[i] = checkValue;
}
Here is the full code:
class Program
{
static void Main(string args)
{
SetArray(1, 10);
SetArray(2, 10);
}
private static void SetArray(int checkValue, int nTimes)
{
const int N = 500_000_000;
int values = new int[N]; // 4 GB
for (int k = 0; k < nTimes; k++) // set array values to 1
{
for (int i = 0; i < values.Length; i++)
{
values[i] = 1;
}
var sw = Stopwatch.StartNew();
Action acc = () =>
{
int tmp1 = 0;
for (int i = 0; i < values.Length; i++)
{
tmp1 = values[i];
if (tmp1 != checkValue) // set only if not equal to checkvalue
{
values[i] = checkValue;
}
}
};
Parallel.Invoke(acc, acc, acc); // Let this run on 3 cores
sw.Stop();
Console.WriteLine($"Set {N * 4 / (1_000_000_000.0f):F1} GB of Memory in {sw.Elapsed.TotalMilliseconds:F0} ms. Initial Value 1. Set Value {checkValue}");
}
}
}
If you let that run you get values like:
// Value not set
Set 2.0 GB of Memory in 439 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 420 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 429 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 393 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 404 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 395 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 419 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 421 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 442 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 422 ms. Initial Value 1. Set Value 1
// Value written
Set 2.0 GB of Memory in 519 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 582 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 543 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 484 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 523 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 540 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 552 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 527 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 535 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 581 ms. Initial Value 1. Set Value 2
That results in a 22% faster performance which can be significant in high performance number crunching scenarios.
To answer the question as it was written:
You can remove the if statement if access to the memory is only single threaded. If multiple threads are working on the same or nearby data false sharing can happen which can cost you up to ca. 20% of memory access performance.
1
If the setter is used by multiple threads without any synchronization that essentially means the produced data are inconsitent, and at this point the processing speed isn't really that important. C# doesn't require writes to non-volatile fields in one thread to be visible in other threads until a volatile field referenced, or alocktaken/released, or a thread created/terminated.
– Joker_vD
8 hours ago
That is a simplified example. Suppose you have a struct with two fields int F1, F2. And you update them in two threads where one updates only F1 and the other F2. There is no overlap in the written data but your performance will be down due to false sharing. That is meant with false sharing. You have a false data dependency due to how caches of the CPU work.
– Alois Kraus
7 hours ago
2
@Joker_vD: If different threads were writing meaningfully-different data, that would be true. False sharing can occur, however, in cases where all threads that would modify something would store the same value or equivalent values. For example, if an object has a field to say whether it has ever done something, setting the flag totruewhen it already is may degrade the performance of other threads trying to read the flag.
– supercat
6 hours ago
add a comment |
This question has gained quite some comments but so far all answers try to reframe the question to address issues with operator overloading or side effects of the setter.
If the setter is using by multiple threads it can really make a difference. The check before set pattern can (you should measure) be useful if you are iterating over the same data with multiple threads which alter the data. The text book name for this phenomena is called false sharing. If you read the data and did verify that it already matches the target value you can omit the write.
If you omit the write the CPU does not need to flush the cache line (a 64 byte block on Intel CPUs) to ensure that other cores see the changed value. If the other core was about to read some other data from that 64 byte block then you just have slowed down your core and increased cross core traffic to synchronize memory contents between CPU caches.
The following sample application shows this effect which also contains the check before write condition:
if (tmp1 != checkValue) // set only if not equal to checkvalue
{
values[i] = checkValue;
}
Here is the full code:
class Program
{
static void Main(string args)
{
SetArray(1, 10);
SetArray(2, 10);
}
private static void SetArray(int checkValue, int nTimes)
{
const int N = 500_000_000;
int values = new int[N]; // 4 GB
for (int k = 0; k < nTimes; k++) // set array values to 1
{
for (int i = 0; i < values.Length; i++)
{
values[i] = 1;
}
var sw = Stopwatch.StartNew();
Action acc = () =>
{
int tmp1 = 0;
for (int i = 0; i < values.Length; i++)
{
tmp1 = values[i];
if (tmp1 != checkValue) // set only if not equal to checkvalue
{
values[i] = checkValue;
}
}
};
Parallel.Invoke(acc, acc, acc); // Let this run on 3 cores
sw.Stop();
Console.WriteLine($"Set {N * 4 / (1_000_000_000.0f):F1} GB of Memory in {sw.Elapsed.TotalMilliseconds:F0} ms. Initial Value 1. Set Value {checkValue}");
}
}
}
If you let that run you get values like:
// Value not set
Set 2.0 GB of Memory in 439 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 420 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 429 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 393 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 404 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 395 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 419 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 421 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 442 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 422 ms. Initial Value 1. Set Value 1
// Value written
Set 2.0 GB of Memory in 519 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 582 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 543 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 484 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 523 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 540 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 552 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 527 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 535 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 581 ms. Initial Value 1. Set Value 2
That results in a 22% faster performance which can be significant in high performance number crunching scenarios.
To answer the question as it was written:
You can remove the if statement if access to the memory is only single threaded. If multiple threads are working on the same or nearby data false sharing can happen which can cost you up to ca. 20% of memory access performance.
1
If the setter is used by multiple threads without any synchronization that essentially means the produced data are inconsitent, and at this point the processing speed isn't really that important. C# doesn't require writes to non-volatile fields in one thread to be visible in other threads until a volatile field referenced, or alocktaken/released, or a thread created/terminated.
– Joker_vD
8 hours ago
That is a simplified example. Suppose you have a struct with two fields int F1, F2. And you update them in two threads where one updates only F1 and the other F2. There is no overlap in the written data but your performance will be down due to false sharing. That is meant with false sharing. You have a false data dependency due to how caches of the CPU work.
– Alois Kraus
7 hours ago
2
@Joker_vD: If different threads were writing meaningfully-different data, that would be true. False sharing can occur, however, in cases where all threads that would modify something would store the same value or equivalent values. For example, if an object has a field to say whether it has ever done something, setting the flag totruewhen it already is may degrade the performance of other threads trying to read the flag.
– supercat
6 hours ago
add a comment |
This question has gained quite some comments but so far all answers try to reframe the question to address issues with operator overloading or side effects of the setter.
If the setter is using by multiple threads it can really make a difference. The check before set pattern can (you should measure) be useful if you are iterating over the same data with multiple threads which alter the data. The text book name for this phenomena is called false sharing. If you read the data and did verify that it already matches the target value you can omit the write.
If you omit the write the CPU does not need to flush the cache line (a 64 byte block on Intel CPUs) to ensure that other cores see the changed value. If the other core was about to read some other data from that 64 byte block then you just have slowed down your core and increased cross core traffic to synchronize memory contents between CPU caches.
The following sample application shows this effect which also contains the check before write condition:
if (tmp1 != checkValue) // set only if not equal to checkvalue
{
values[i] = checkValue;
}
Here is the full code:
class Program
{
static void Main(string args)
{
SetArray(1, 10);
SetArray(2, 10);
}
private static void SetArray(int checkValue, int nTimes)
{
const int N = 500_000_000;
int values = new int[N]; // 4 GB
for (int k = 0; k < nTimes; k++) // set array values to 1
{
for (int i = 0; i < values.Length; i++)
{
values[i] = 1;
}
var sw = Stopwatch.StartNew();
Action acc = () =>
{
int tmp1 = 0;
for (int i = 0; i < values.Length; i++)
{
tmp1 = values[i];
if (tmp1 != checkValue) // set only if not equal to checkvalue
{
values[i] = checkValue;
}
}
};
Parallel.Invoke(acc, acc, acc); // Let this run on 3 cores
sw.Stop();
Console.WriteLine($"Set {N * 4 / (1_000_000_000.0f):F1} GB of Memory in {sw.Elapsed.TotalMilliseconds:F0} ms. Initial Value 1. Set Value {checkValue}");
}
}
}
If you let that run you get values like:
// Value not set
Set 2.0 GB of Memory in 439 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 420 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 429 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 393 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 404 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 395 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 419 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 421 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 442 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 422 ms. Initial Value 1. Set Value 1
// Value written
Set 2.0 GB of Memory in 519 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 582 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 543 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 484 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 523 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 540 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 552 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 527 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 535 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 581 ms. Initial Value 1. Set Value 2
That results in a 22% faster performance which can be significant in high performance number crunching scenarios.
To answer the question as it was written:
You can remove the if statement if access to the memory is only single threaded. If multiple threads are working on the same or nearby data false sharing can happen which can cost you up to ca. 20% of memory access performance.
This question has gained quite some comments but so far all answers try to reframe the question to address issues with operator overloading or side effects of the setter.
If the setter is using by multiple threads it can really make a difference. The check before set pattern can (you should measure) be useful if you are iterating over the same data with multiple threads which alter the data. The text book name for this phenomena is called false sharing. If you read the data and did verify that it already matches the target value you can omit the write.
If you omit the write the CPU does not need to flush the cache line (a 64 byte block on Intel CPUs) to ensure that other cores see the changed value. If the other core was about to read some other data from that 64 byte block then you just have slowed down your core and increased cross core traffic to synchronize memory contents between CPU caches.
The following sample application shows this effect which also contains the check before write condition:
if (tmp1 != checkValue) // set only if not equal to checkvalue
{
values[i] = checkValue;
}
Here is the full code:
class Program
{
static void Main(string args)
{
SetArray(1, 10);
SetArray(2, 10);
}
private static void SetArray(int checkValue, int nTimes)
{
const int N = 500_000_000;
int values = new int[N]; // 4 GB
for (int k = 0; k < nTimes; k++) // set array values to 1
{
for (int i = 0; i < values.Length; i++)
{
values[i] = 1;
}
var sw = Stopwatch.StartNew();
Action acc = () =>
{
int tmp1 = 0;
for (int i = 0; i < values.Length; i++)
{
tmp1 = values[i];
if (tmp1 != checkValue) // set only if not equal to checkvalue
{
values[i] = checkValue;
}
}
};
Parallel.Invoke(acc, acc, acc); // Let this run on 3 cores
sw.Stop();
Console.WriteLine($"Set {N * 4 / (1_000_000_000.0f):F1} GB of Memory in {sw.Elapsed.TotalMilliseconds:F0} ms. Initial Value 1. Set Value {checkValue}");
}
}
}
If you let that run you get values like:
// Value not set
Set 2.0 GB of Memory in 439 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 420 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 429 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 393 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 404 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 395 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 419 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 421 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 442 ms. Initial Value 1. Set Value 1
Set 2.0 GB of Memory in 422 ms. Initial Value 1. Set Value 1
// Value written
Set 2.0 GB of Memory in 519 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 582 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 543 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 484 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 523 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 540 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 552 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 527 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 535 ms. Initial Value 1. Set Value 2
Set 2.0 GB of Memory in 581 ms. Initial Value 1. Set Value 2
That results in a 22% faster performance which can be significant in high performance number crunching scenarios.
To answer the question as it was written:
You can remove the if statement if access to the memory is only single threaded. If multiple threads are working on the same or nearby data false sharing can happen which can cost you up to ca. 20% of memory access performance.
answered 8 hours ago
Alois KrausAlois Kraus
10.2k2452
10.2k2452
1
If the setter is used by multiple threads without any synchronization that essentially means the produced data are inconsitent, and at this point the processing speed isn't really that important. C# doesn't require writes to non-volatile fields in one thread to be visible in other threads until a volatile field referenced, or alocktaken/released, or a thread created/terminated.
– Joker_vD
8 hours ago
That is a simplified example. Suppose you have a struct with two fields int F1, F2. And you update them in two threads where one updates only F1 and the other F2. There is no overlap in the written data but your performance will be down due to false sharing. That is meant with false sharing. You have a false data dependency due to how caches of the CPU work.
– Alois Kraus
7 hours ago
2
@Joker_vD: If different threads were writing meaningfully-different data, that would be true. False sharing can occur, however, in cases where all threads that would modify something would store the same value or equivalent values. For example, if an object has a field to say whether it has ever done something, setting the flag totruewhen it already is may degrade the performance of other threads trying to read the flag.
– supercat
6 hours ago
add a comment |
1
If the setter is used by multiple threads without any synchronization that essentially means the produced data are inconsitent, and at this point the processing speed isn't really that important. C# doesn't require writes to non-volatile fields in one thread to be visible in other threads until a volatile field referenced, or alocktaken/released, or a thread created/terminated.
– Joker_vD
8 hours ago
That is a simplified example. Suppose you have a struct with two fields int F1, F2. And you update them in two threads where one updates only F1 and the other F2. There is no overlap in the written data but your performance will be down due to false sharing. That is meant with false sharing. You have a false data dependency due to how caches of the CPU work.
– Alois Kraus
7 hours ago
2
@Joker_vD: If different threads were writing meaningfully-different data, that would be true. False sharing can occur, however, in cases where all threads that would modify something would store the same value or equivalent values. For example, if an object has a field to say whether it has ever done something, setting the flag totruewhen it already is may degrade the performance of other threads trying to read the flag.
– supercat
6 hours ago
1
1
If the setter is used by multiple threads without any synchronization that essentially means the produced data are inconsitent, and at this point the processing speed isn't really that important. C# doesn't require writes to non-volatile fields in one thread to be visible in other threads until a volatile field referenced, or a
lock taken/released, or a thread created/terminated.– Joker_vD
8 hours ago
If the setter is used by multiple threads without any synchronization that essentially means the produced data are inconsitent, and at this point the processing speed isn't really that important. C# doesn't require writes to non-volatile fields in one thread to be visible in other threads until a volatile field referenced, or a
lock taken/released, or a thread created/terminated.– Joker_vD
8 hours ago
That is a simplified example. Suppose you have a struct with two fields int F1, F2. And you update them in two threads where one updates only F1 and the other F2. There is no overlap in the written data but your performance will be down due to false sharing. That is meant with false sharing. You have a false data dependency due to how caches of the CPU work.
– Alois Kraus
7 hours ago
That is a simplified example. Suppose you have a struct with two fields int F1, F2. And you update them in two threads where one updates only F1 and the other F2. There is no overlap in the written data but your performance will be down due to false sharing. That is meant with false sharing. You have a false data dependency due to how caches of the CPU work.
– Alois Kraus
7 hours ago
2
2
@Joker_vD: If different threads were writing meaningfully-different data, that would be true. False sharing can occur, however, in cases where all threads that would modify something would store the same value or equivalent values. For example, if an object has a field to say whether it has ever done something, setting the flag to
true when it already is may degrade the performance of other threads trying to read the flag.– supercat
6 hours ago
@Joker_vD: If different threads were writing meaningfully-different data, that would be true. False sharing can occur, however, in cases where all threads that would modify something would store the same value or equivalent values. For example, if an object has a field to say whether it has ever done something, setting the flag to
true when it already is may degrade the performance of other threads trying to read the flag.– supercat
6 hours ago
add a comment |
Yes, this if is useless. You check if the value are the same (and set it if not).
When the !=-operator is not overloaded, then is this:
private double ageValue;
public double Age
{
get { return ageValue; }
set
{
if (value != ageValue)
{
ageValue = value;
}
}
}
same to
private double ageValue;
public double Age
{
get { return ageValue; }
set { ageValue = value; }
}
Is it useless if the they are properties with getters and setters that perform other operations?
– Amy
10 hours ago
Its the setter-method (look at the question). There can not be any other actions. The only thing (but happend not often out there) is a overloaded!=-operator.
– user6537157
10 hours ago
Yes, the question was expanded with additional context.
– Amy
10 hours ago
Why is the only answer that addresses OP's actual question rather than a "what if" so heavily downvoted?
– helrich
10 hours ago
Because before revision 4 of the question, this answer was wrong. Codor's answer was the only one that was correct.
– Amy
10 hours ago
|
show 3 more comments
Yes, this if is useless. You check if the value are the same (and set it if not).
When the !=-operator is not overloaded, then is this:
private double ageValue;
public double Age
{
get { return ageValue; }
set
{
if (value != ageValue)
{
ageValue = value;
}
}
}
same to
private double ageValue;
public double Age
{
get { return ageValue; }
set { ageValue = value; }
}
Is it useless if the they are properties with getters and setters that perform other operations?
– Amy
10 hours ago
Its the setter-method (look at the question). There can not be any other actions. The only thing (but happend not often out there) is a overloaded!=-operator.
– user6537157
10 hours ago
Yes, the question was expanded with additional context.
– Amy
10 hours ago
Why is the only answer that addresses OP's actual question rather than a "what if" so heavily downvoted?
– helrich
10 hours ago
Because before revision 4 of the question, this answer was wrong. Codor's answer was the only one that was correct.
– Amy
10 hours ago
|
show 3 more comments
Yes, this if is useless. You check if the value are the same (and set it if not).
When the !=-operator is not overloaded, then is this:
private double ageValue;
public double Age
{
get { return ageValue; }
set
{
if (value != ageValue)
{
ageValue = value;
}
}
}
same to
private double ageValue;
public double Age
{
get { return ageValue; }
set { ageValue = value; }
}
Yes, this if is useless. You check if the value are the same (and set it if not).
When the !=-operator is not overloaded, then is this:
private double ageValue;
public double Age
{
get { return ageValue; }
set
{
if (value != ageValue)
{
ageValue = value;
}
}
}
same to
private double ageValue;
public double Age
{
get { return ageValue; }
set { ageValue = value; }
}
edited 10 hours ago
answered 10 hours ago
user6537157user6537157
345114
345114
Is it useless if the they are properties with getters and setters that perform other operations?
– Amy
10 hours ago
Its the setter-method (look at the question). There can not be any other actions. The only thing (but happend not often out there) is a overloaded!=-operator.
– user6537157
10 hours ago
Yes, the question was expanded with additional context.
– Amy
10 hours ago
Why is the only answer that addresses OP's actual question rather than a "what if" so heavily downvoted?
– helrich
10 hours ago
Because before revision 4 of the question, this answer was wrong. Codor's answer was the only one that was correct.
– Amy
10 hours ago
|
show 3 more comments
Is it useless if the they are properties with getters and setters that perform other operations?
– Amy
10 hours ago
Its the setter-method (look at the question). There can not be any other actions. The only thing (but happend not often out there) is a overloaded!=-operator.
– user6537157
10 hours ago
Yes, the question was expanded with additional context.
– Amy
10 hours ago
Why is the only answer that addresses OP's actual question rather than a "what if" so heavily downvoted?
– helrich
10 hours ago
Because before revision 4 of the question, this answer was wrong. Codor's answer was the only one that was correct.
– Amy
10 hours ago
Is it useless if the they are properties with getters and setters that perform other operations?
– Amy
10 hours ago
Is it useless if the they are properties with getters and setters that perform other operations?
– Amy
10 hours ago
Its the setter-method (look at the question). There can not be any other actions. The only thing (but happend not often out there) is a overloaded
!=-operator.– user6537157
10 hours ago
Its the setter-method (look at the question). There can not be any other actions. The only thing (but happend not often out there) is a overloaded
!=-operator.– user6537157
10 hours ago
Yes, the question was expanded with additional context.
– Amy
10 hours ago
Yes, the question was expanded with additional context.
– Amy
10 hours ago
Why is the only answer that addresses OP's actual question rather than a "what if" so heavily downvoted?
– helrich
10 hours ago
Why is the only answer that addresses OP's actual question rather than a "what if" so heavily downvoted?
– helrich
10 hours ago
Because before revision 4 of the question, this answer was wrong. Codor's answer was the only one that was correct.
– Amy
10 hours ago
Because before revision 4 of the question, this answer was wrong. Codor's answer was the only one that was correct.
– Amy
10 hours ago
|
show 3 more comments
TheOrlexx is a new contributor. Be nice, and check out our Code of Conduct.
TheOrlexx is a new contributor. Be nice, and check out our Code of Conduct.
TheOrlexx is a new contributor. Be nice, and check out our Code of Conduct.
TheOrlexx is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55300081%2fredundant-comparison-if-before-assignment%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
14
assuming ageValue isn't a property, but is only a variable then there is no point. If ageValue is a property, maybe something happens in the set?
– Alex Anderson
10 hours ago
2
Without greater context (is
ageValuebound to a display field? IsageValuea property?), this question has only answers that are not very helpful.– crashmstr
10 hours ago
8
So you only set the ageValue when the value is something new. Right here it doesn't make sense to have an
ifbut in other cases when we do more than just set the value it can save time. For example, in a WPF MVVM application afterageValue = valuewe'd most likely callNotifyPropertyChangedso the GUI knows that a property changed, but we'd only want to do this if our property actually changed– MindSwipe
10 hours ago
4
With regard to your added/edited code: yes, the
ifis redundant in this particular code example you have given.– elgonzo
10 hours ago
2
Related: Is it a sensible optimization to check whether a variable holds a specific value before writing that value?
– GSerg
7 hours ago