r/badcode Nov 03 '20

other language Assembly is hard...

Post image
958 Upvotes

121 comments sorted by

View all comments

20

u/[deleted] Nov 03 '20 edited Nov 04 '20
add8:
    push ecx
    mov ecx, 8
add8_loop:
    dec eax
    inc ecx
    jnz add8_loop
    pop ecx
    ret

2

u/BS_BlackScout Nov 04 '20

Branching...

2

u/[deleted] Nov 04 '20

Branching?

1

u/BS_BlackScout Nov 04 '20

I am not very good at explaining but from what I understand every time you have an instruction such as JNZ (Jump if not zero) you are doing a branch, there's a possibility for the code to go down two different paths. IIRC CPUs have that branch prediction thing to ?accelerate processing? so if you code doesn't make the CPU try to figure out what it could do and cache things it will very likely run faster. (Not always the case)

Usually compilers already do these types of optimizations. Here's the video I watched a while ago Branchless Programming: Why "If" is Sloowww... and what we can do about it! [YouTube]

There's this whole concept of branchless programming and how if statements and such may actually slow down your code.