0

I'm using a BYTE variable in assembler to hold partial statements before they're copied to a permanent location. I'm trying to figure out how I could clear that after each new entry. I tried moving an empty variable into it, but that only replaced the first character space of the variable. Any help would be much appreciated, thanks!

xboxmods
  • 53
  • 2
  • 3
  • 6

2 Answers2

3

Use XOR instead of MOV. It's faster.

XOR r1, r1
Trevor Arjeski
  • 2,108
  • 1
  • 24
  • 40
  • I tried xor, but it fails to build with variables. However, I use it regularly with registers. – xboxmods Oct 23 '11 at 03:03
  • @xboxmods `AND byte [var],0h`? – Trevor Arjeski Oct 24 '11 at 13:30
  • @xboxmods because you can't have memory in both instruction arguments. You must either move from an immediate or a register to memory – phuclv Mar 21 '15 at 13:41
  • What takes time is the loading of the constant `0`. So the only fastest way to do this AFAIK is by using `XOR r1, r1`. – ljleb May 16 '20 at 09:21
  • That's true for registers, yes. [What is the best way to set a register to zero in x86 assembly: xor, mov or and?](https://stackoverflow.com/q/33666617). For one byte in memory, `AND` is useless: `mov byte [var], 0` is the same size. For wider memory operands, AND can still be `imm8`, while unfortunately `mov dword [var], 0` can only be encoded with an imm32, 4 bytes of zeros. So AND is smaller but slower. – Peter Cordes Jun 16 '21 at 09:15
1

For a variable (assuming your var is stored in the memory):

mov var1, 0

For an array (as far as I got, that's what you are talking about?):

xor al, al
lea edi, var1
mov ecx, <var1_array_size>
cld
rep stosb
Desu_Never_Lies
  • 690
  • 3
  • 10
  • `xor eax,eax` is [a more efficient way to zero AL](https://stackoverflow.com/questions/33666617/what-is-the-best-way-to-set-a-register-to-zero-in-x86-assembly-xor-mov-or-and), and `mov edi, OFFSET var1` is more efficient than LEA (unless this is 64-bit code where that's a RIP-relative LEA in MASM syntax). – Peter Cordes Jun 16 '21 at 09:31
  • `rep stosb` with a byte count vs. `rep stosd` with a dword count depends on the CPU: a few CPUs with the ERMSB feature have a `rep stosb` that's actually faster, but modern CPUs handle `rep stosd` just as efficiently as `rep stosb`. While older CPUs handle it more efficiently, at least for non-tiny memsets. [Enhanced REP MOVSB for memcpy](https://stackoverflow.com/q/43343231) – Peter Cordes Jun 16 '21 at 09:31