user5460725
user5460725

Reputation:

Is checking if a value is 0 faster than just overwriting it?

Let's just say I have an array which contains some numbers contained between 1 and 9, and another array of 9 elements which contains every number from 1 to 9 (1, 2, 3, ... 9). I want to read every number from the first array, and when I read the number X, put to 0 the X value in the second array (which would be contained in second_array[X-1]). Is it faster for the CPU to do this:

//size is the size of the first array
int temp = 0;

for(int i; i < size; i++)
{
    temp = first_array[i];
    if(second_array[temp-1] != 0) second_array[temp-1]= 0;
}

Or the same without the control:

int temp = 0;

for(int i; i < size; i++)
{
    temp = first_array[i];
    second_array[temp-1]= 0;
}

To be clear: does it take more time to make a control on the value, or to overwrite it? I need my code to execute as fast as possible, so every nanosecond saved would be useful. Thanks in advance.

Upvotes: 1

Views: 223

Answers (4)

Dorus
Dorus

Reputation: 7546

You can just go with:

for(int i = 0; i < size; i++)
{
    second_array[first_array[i]-1]= 0;
}

Even if the check is faster (i doubt it), it would only be faster if a large part of the second_array started as 0, as any non 0 location requires two operations.

Anyway, the best way to figure out the answer to these kind of questions is to use run it and benchmark! A quick benchmark on my side shows it is 60% slower if second_array does not contain zero's, but 50% faster when second_array is all zero's! That would lead me to conclude the check is faster if more than 55% of second_array start zeroed out.

Upvotes: 0

Audrius Meškauskas
Audrius Meškauskas

Reputation: 21728

If the value is checked repeatedly, it may be cached in the CPU cache and accessed much faster from there than from the main RAM. Differently, writing the value requires this value to make all the way to the main memory that may take more time. Writing may be deferred, but the dirty cache row must be flushed sooner or later.

Hence the version that only repeatedly reads may be faster than the version that repeatedly writes.

Upvotes: 0

RockAndRoll
RockAndRoll

Reputation: 2277

Writing data to memory is always fast when comparing to if condition.

Reason - to compare two values,you need to read them first and then you need to perform comparison.While in other case,you are simply writing data to memory which does not care about anything.

Upvotes: 0

hotzst
hotzst

Reputation: 7496

The second version is more performant, as is does not require the check, which will happen in every iteration of the loop and only in one case yield true.

Furthermore you can improve even more if you write:

for(int i; i < size; i++)
{
    temp = first_array[i];
}
second_array[size-1]= 0;

Upvotes: 2

Related Questions