Jayesh Jayesh - 11 months ago 38
C Question

Which code will execute faster in C?

I saw the following code(Ques. 3) on PUZZLERSWORLD.COM site.

Code 1 :

for(i=0; i<1000; i++)
for(j=0; j<100; j++)
x = y;


Code 2 :

for(i=0; i<100; i++)
for(j=0; j<1000; j++)
x = y;


Which code will execute faster?

Options:

a) Code 1 and Code 2 are of same speed,
b) Code 1,
c) Code 2,
d) Can't Say


Answer:

C


So, I have a question, Why second code faster then first?

Answer Source

Unless y is declared as volatile, both codes can be reduced into:

x = y;

Example:

int f(int y)
{
    int x;

    for (int i = 0; i < 1000; i++)
        for (int j = 0; j < 100; j++)
            x = y;
    return x;
}

yields:

f(int):
        mov     eax, edi
        ret
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download