When a global variable is used inside a function(C/C++), whether it'll be taken directly from registers or from stack?
Why bound loops(for loops) are considered to have more scope for optimization than nobound loops(while loop/do while)?
Why returning a value is not as good as passing the value by reference?
If possible plz give assembly level descriptions.
1) It will be taken from an address allocated as part of the application load. ie A global variable is simply an address in the process's virtual address space. If that global has been used recently the compiler may be able to cache it in a register.
2) They don't.
3) Returning a value often requires a copy of the data. If the data is a simple type (such as int or float) then it can and will be returned via a register. If the object is too large to fit in a register then the compiler must allocate space for the object on the stack and then copy the data being returned into this allocated space. Passing the value as a reference is, usually, implemented by passing a pointer to the data. Therefore you return the value by modifying the data at that memory address directly. No copy takes place and hence its faster. Do note, though, that Return Value Optimisation (RVO) can mean that there is no win to passing the return value in as a reference. Equally,a s pointed out in the comments, C++0x's new move constructor can also provide the same bonuses as RVO.
No need to explain any of those using assembler examples, IMO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With