x86-64最小指令长度strlen实现技术咨询
First, let's start with a critical observation: your current code has a logic bug that returns the wrong length, and fixing it also gives you an immediate size optimization.
The Bug & Quick Fix
Your final dec ecx instruction is incorrect. Let's walk through the math step by step:
- You initialize
ecx = -1(0xFFFFFFFF) andal = 0. repne scasbscans until it hits a null byte, decrementingecxonce for every non-null byte it encounters. For a string of lengthn, this meansecxends up as-(n + 1)(since we scannednnon-null bytes, each decrementingecxfrom its starting value of -1).not ecxflips the bits of-(n+1), which gives you exactlyn(the correct strlen result).- Adding
dec ecxthen subtracts 1, leaving you withn-1—which is wrong for all non-empty strings.
Removing the dec ecx fixes the bug and cuts your total instruction length from 11 bytes to 9 bytes:
xor eax,eax ; 2 bytes (sets al=0) or ecx,-1 ; 3 bytes (sets ecx=-1) repne scasb ; 2 bytes not ecx ; 2 bytes
Total: 9 bytes, with the correct strlen value stored in ecx.
Further Size Optimization
Is there a way to shrink this even more? Let's explore the options:
- Setting
ecx=-1: Youror ecx,-1is the shortest possible way to do this (3 bytes). Alternatives likexor ecx,ecx; dec ecxcost 4 bytes total, which is longer. - Setting
al=0:xor eax,eaxis 2 bytes, same asmov al,0—no gain here. - 64-bit register usage: Using
rcxinstead ofecxwould requireor rcx,-1(4 bytes), which adds a byte, so that's worse (especially since you noted the max length is Int32).
At 9 bytes, this is already extremely compact for a correct repne scasb-based strlen. I don't know of any valid x86-64 instruction sequences that can get this shorter while maintaining correctness for all valid input strings.
Potential Edge Cases & Caveats
Even with the bug fixed, keep these in mind for your use case:
- Null-termination requirement: Like standard
strlen, this relies entirely on the input string being null-terminated. If the string has no null byte, it will scan 4GB of memory (sinceecxstarts at -1, the maximum Int32 value) untilecxunderflows to 0, which will cause invalid memory accesses or wrong results. - Register clobbering: This implementation modifies
rax,rcx, andrdi. In code golf or demo scenarios, this is usually acceptable, but make sure your environment allows these registers to be overwritten. - Performance: While size-optimized,
repne scasbisn't the fastest strlen implementation (especially for long strings), but that's irrelevant for code golf/demo use cases where size is the priority.
内容的提问来源于stack exchange,提问作者Kamil.S

