void func(int depth){
if(depth== 0) return;
int number(12345);
cout << number; //it does something with number
func(--depth);
}
void func2(int depth){
if(depth== 0) return;
{
int number(12345);
cout << number; //it does something with number
}
func2(--depth);
}
void main(){
func(10); //will this function cost more memory?
func2(10);//will this function cost less memory?
}
Run Code Online (Sandbox Code Playgroud)
你好.我这里有两个功能.func2会花费更少的内存,因为它的数字(12345)被"{}"封装,所以当func2调用下一次迭代时,数字(12345)可以超出范围并消失吗?
我相信func会花费更多,因为它的数量(12345)即使到达下一次迭代时也不在范围之外?
假设我们有AMD/Intel x86_64架构,我们的编译器是GCC.
让我们获取装配输出(-O2 -S)并分析:
func:
.LFB1560:
pushq %rsi
.seh_pushreg %rsi
pushq %rbx
.seh_pushreg %rbx
subq $40, %rsp
.seh_stackalloc 40
.seh_endprologue
movl %ecx, %ebx
testl %ecx, %ecx
je .L3
movq .refptr._ZSt4cout(%rip), %rsi
.p2align 4,,10
.L5:
movl $12345, %edx
movq %rsi, %rcx
call _ZNSolsEi
subl $1, %ebx
jne .L5
.L3:
addq $40, %rsp
popq %rbx
popq %rsi
ret
.seh_endproc
func2:
.LFB2046:
pushq %rsi
.seh_pushreg %rsi
pushq %rbx
.seh_pushreg %rbx
subq $40, %rsp
.seh_stackalloc 40
.seh_endprologue
movl %ecx, %ebx
testl %ecx, %ecx
je .L10
movq .refptr._ZSt4cout(%rip), %rsi
.p2align 4,,10
.L12:
movl $12345, %edx
movq %rsi, %rcx
call _ZNSolsEi
subl $1, %ebx
jne .L12
.L10:
addq $40, %rsp
popq %rbx
popq %rsi
ret
.seh_endproc
Run Code Online (Sandbox Code Playgroud)
如您所见,两个功能完全相同.
| 归档时间: |
|
| 查看次数: |
161 次 |
| 最近记录: |