Question:
Why n++ executes faster than n+1?
Answer:
The expression n++ requires a single machine instruction such as INR to carry out the increment operation whereas, n+1 requires more instructions to carry out this operation. Source: CoolInterview.com
The expression n++ requires a single machine instruction such as INR to carry out the increment operation whereas, n+1 requires more instructions to carry out this operation. If n+1 is executed,the value of n should be stored in memory,then bring to CPU and perform addition in CPU and then write to memory back.Hence,CPU time is consumed more. Compilers nowadays are smarter,if it encounters n+1,it replaces it by n++.Hence,it really doesn't matters for user since optimization is gained by compiler. Source: CoolInterview.com
Answered by: Lohit.A.H | Date: 7/28/2009
| Contact Lohit.A.H
n++ requires only to increment the value of n by one,while n=n+1 means first add 1 to the n and then perform the assignment operation = thus it requires two tasks to be performed while n++ requires only one task to be performed. Source: CoolInterview.com
Answered by: abhay | Date: 11/11/2009
| Contact abhay
It depends on the target architecture. If the architecture does not support the INC/ DEC instruction, then n++ and n = n +1 will be same. Means, same kind of instruction will be generated. Source: CoolInterview.com
Answered by: anamika | Date: 12/10/2009
| Contact anamika
all high level lang are converted first to machine instruction and its the machine instruction on which the speed of execution of our program depend so n=1 means use of add instr of var and store value it it too time taking so we prefer n++ for faster execution. Source: CoolInterview.com
Answered by: Nishant jichkar | Date: 1/22/2010
| Contact Nishant jichkar
If you have the better answer, then send it to us. We will display your answer after the approval.
Rules to Post Answers in CoolInterview.com:-
- There should not be any Spelling Mistakes.
- There should not be any Gramatical Errors.
- Answers must not contain any bad words.
- Answers should not be the repeat of same answer, already approved.
- Answer should be complete in itself.
|