mercredi 22 juin 2016

Why C/C++ is slower than Assembly and other low level languages?

I write a code, doing nothing in C++

void main(void){

}

and Assembly.

.global _start
.text

_start:
    mov $60, %rax
    xor %rdi, %rdi 
    syscall

I compile the C code and compile and link Assembly code. I make a comparison between two executable file with time command.

Assembly

time ./Assembly

real    0m0.001s
user    0m0.000s
sys     0m0.000s

C

time ./C

real    0m0.002s
user    0m0.000s
sys     0m0.000s

Assembly is two times faster than C. I disassemble the codes, in Assembly code, there was only four lines code (Same). In the C code, there was tons of unnecessary code writed for linking main to _start. In main there was four lines code, three of that is writed for making impossible (you can't access to a function's variable from outside of the function blog) to access 'local' (like function veriables) variables from outside of 'block' (like function blocks).

push %rbp ; push base pointer.
mov  %rsp, %rbp ; copy value of stack pointer to base pointer, stack pointer is using for saving variables.
pop  %rbp ; 'local' variables are removed, because we pop the base pointer 
retq ; ?

What is why of that?

Aucun commentaire:

Enregistrer un commentaire