Efficiency Issue - true or false?

R

rahul.batra

This is supposed to be a very general question.
Consider the following 2 code samples:

Code Sample 1:

for (int i=0; i<n; ++i)
{
for (int j=0; j<n; ++j)
{
/* Do something here */
}
}



Code Sample 2:
(Now we declare j in advance rather than each time inside the i loop
as in code sample 1)

int j;
for (int i=0; i<n; ++i)
{
for (j=0; j<n; ++j) // Notice the differnce here, now
{
/* Do something here */
}
}


Is code sample 2 faster than code sample 1?
Plz specify the reasons too.
 
C

Chris Jefferson

This is supposed to be a very general question.
Consider the following 2 code samples:

Code Sample 1:

for (int i=0; i<n; ++i)
{
for (int j=0; j<n; ++j)
{
/* Do something here */
}
}



Code Sample 2:
(Now we declare j in advance rather than each time inside the i loop
as in code sample 1)

int j;
for (int i=0; i<n; ++i)
{
for (j=0; j<n; ++j) // Notice the differnce here, now
{
/* Do something here */
}
}


Is code sample 2 faster than code sample 1?
Plz specify the reasons too.

No, they will produce exactly the same code. The reason is that
"creating an int" doesn't actually require any work at all, except
marking some register / piece of memory in which it will live.

You could find that if j was a complex class, the second might be
faster, although in most cases it probably wouldn't be, as "complexclass
j = 0" would be mapped to "complexclass j(0)" and in many cases
constructing a new object may be faster than assigning to an existing one.

Chris
 
I

Ioannis Vranos

This is supposed to be a very general question.
Consider the following 2 code samples:

Code Sample 1:

for (int i=0; i<n; ++i)
{
for (int j=0; j<n; ++j)
{
/* Do something here */
}
}



Code Sample 2:
(Now we declare j in advance rather than each time inside the i loop
as in code sample 1)

int j;
for (int i=0; i<n; ++i)
{
for (j=0; j<n; ++j) // Notice the differnce here, now
{
/* Do something here */
}
}


Is code sample 2 faster than code sample 1?
Plz specify the reasons too.


In both cases two ints are created and used. In subsequent loops with
more int counters, you can't expect any additional cost either because
the compiler can perform further optimisations since it knows that the
variables are used for loop counters only, like placing them in a register.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top