c++ - dynamic memory management scenario -
should 1 use dynamic memory allocation when 1 knows variable not needed before goes out of scope?
for example in following function:
void func(){ int =56; //do i, not needed past point for(int t; t<1000000; t++){ //code } }
say 1 needed small section of function, worthwhile deleting not needed in long loop?
as borgleader said:
a) micro (and premature) optimization, meaning don't worry it. b) in particular case, dynamically allocation might hurt performance. tl;dr; profile first, optimize later
as example, compiled following 2 programs assembly (using g++ -s
flag no optimisation enabled).
creating i
on stack:
int main(void) { int = 56; += 5; for(int t = 0; t<1000; t++) {} return 0; }
dynamically:
int main(void) { int* = new int(56); *i += 5; delete i; for(int t = 0; t<1000; t++) {} return 0; }
the first program compiled to:
movl $56, -8(%rbp) # store 56 on stack (int = 56) addl $5, -8(%rbp) # add 5 (i += 5) movl $0, -4(%rbp) # initialize loop index (int t = 0) jmp .l2 # begin loop (goto .l2.) .l3: addl $1, -4(%rbp) # increment index (t++) .l2: cmpl $999, -4(%rbp) # check loop condition (t<1000) setle %al testb %al, %al jne .l3 # if (t<1000) goto .l3. movl $0, %eax # return 0
and second:
subq $16, %rsp # allocate memory (new) movl $4, %edi call _znwm movl $56, (%rax) # store 56 in *i movq %rax, -16(%rbp) movq -16(%rbp), %rax # add 5 movl (%rax), %eax leal 5(%rax), %edx movq -16(%rbp), %rax movl %edx, (%rax) movq -16(%rbp), %rax # free memory (delete) movq %rax, %rdi call _zdlpv movl $0, -4(%rbp) # initialize loop index (int t = 0) jmp .l2 # begin loop (goto .l2.) .l3: addl $1, -4(%rbp) # increment index (t++) .l2: cmpl $999, -4(%rbp) # check loop condition (t<1000) setle %al testb %al, %al jne .l3 # if (t<1000) goto .l3. movl $0, %eax # return 0
in above assembly output, can see strait away there significant difference between number of commands being executed. if compile same programs optimisation turned on. first program produced result:
xorl %eax, %eax # equivalent return 0;
the second produced:
movl $4, %edi call _znwm movl $61, (%rax) # smart compiler knows 56+5 = 61 movq %rax, %rdi call _zdlpv xorl %eax, %eax addq $8, %rsp
with optimisation on, compiler becomes pretty powerful tool improving code, in cases can detect program returns 0 , rid of unnecessary code. when use dynamic memory in code above, program still has request , free dynamic memory, can't optimise out.
Comments
Post a Comment