MButler
MButler

Reputation: 61

In a loop, is it more efficient to set a state value every time or to check to see if it has changed and then set it?

I'm in a situation where I'm iterating through a number of records and setting state information based on the data in those record. Something like this (not real code, just a simplification):

StateObject state;
ConcurrentQueue<Record> records;

while(!records.IsEmpty()) 
{
  //set state here based on the next record
}

So, would it be more efficient/better practice to

{
  //set state here based on the next record
  Record r = records.next();
  state = r.state;
}

or

{
  //set state here based on the next record
  Record r = records.next();
  if(state != r.state)
    state = r.state;
}

Upvotes: 0

Views: 85

Answers (3)

Steve Wellens
Steve Wellens

Reputation: 20620

Testing is expensive, I simplified your code to this:

int x = 5;

if (x == 5)
    x = 4;

x = 4;

Here is the disassembled code:

                int x = 5;
00000036  mov         dword ptr [rsp+20h],5 

            if (x == 5)
0000003e  xor         eax,eax 
00000040  cmp         dword ptr [rsp+20h],5 
00000045  setne       al   
00000048  mov         dword ptr [rsp+28h],eax 
0000004c  movzx       eax,byte ptr [rsp+28h] 
00000051  mov         byte ptr [rsp+24h],al 
00000055  movzx       eax,byte ptr [rsp+24h] 
0000005a  test        eax,eax 
0000005c  jne         0000000000000066 
                x = 4;
0000005e  mov         dword ptr [rsp+20h],4 

            x = 4;
00000066  mov         dword ptr [rsp+20h],4 

That being said, premature optimization is a waste of time. A database call may take one second, the above call may take .00000001 second.

Write the code that is simplest, optimize it later.

Upvotes: 0

Dan Puzey
Dan Puzey

Reputation: 34200

As you said yourself, this is a simplification. The actual answer depends on the specifics of your situation: you could be running to a database on the other side of the world, in which case an update might be prohibitively expensive. Alternatively, your state variable could be a massively complex type that is expensive to compare.

As @harold said in his comment: "try it." Profile your code and gain some understanding of what's expensive and what's not. Chances are the results will not be what you expect!

Upvotes: 0

Tushar Chhabhaiya
Tushar Chhabhaiya

Reputation: 700

it's totally depends on your type of records. in some case 1st is better and in some case 2nd one is better.

Upvotes: 2

Related Questions