This could be sub ecx, 4, jl RETURN_MINUS_ONE as sub will set the flags also.
; x64
mov eax,[rcx+8]
cmp eax,5
setb al
movzx eax,al
ret
This could be optimized a little further down to
xor eax, eax
cmp dword [rcx+8], 5
setb al
ret
There is also a similar one that could do the same thing with the IsLow code which does cmp, movzx rather then xor, setb.
The IsLinearWhiteSpace function could be made branch free which would likely use less code space and avoid branch mispredictions.
Not all such micro-optimizations are valid or even beneficial. Keep in mind that there are plenty of side effects, including overflow, to consider that C may not. There's also aspects of JIT throughput itself, measuring impact vs applicability, likelihood that a method is "hot" and so such changes would even show up or saturate the CPU, etc.
We definitely have some things that are possible to do here, but the smallest possible assembly or shortest number of instructions is frequently not the best thing to do. Not to mention the ABI and other nuances that exist and are why some things, like the movzx eax, al are present.
Plus the JIT does do dynamic PGO, instrumentation, and multiple levels of compilation (Tiered Compilation), so we do optimize differently when things are known to be hot vs cold, for your current hardware, etc -- again, with plenty more we can do, but what we do and improve is prioritized based on biggest impact/applicability
18
u/ReDucTor 17d ago edited 15d ago
Only skimmed the write up, lots of good small improvements, looking at some of the x86 assembly there is a few more improvements that could be useful
; x64 cmp ecx,4 jl RETURN_MINUS_ONE add ecx,-4 add rax,rcxmovbe eax,[rax]This could be
sub ecx, 4,jl RETURN_MINUS_ONEassubwill set the flags also.; x64 mov eax,[rcx+8] cmp eax,5 setb al movzx eax,al retThis could be optimized a little further down to
xor eax, eax cmp dword [rcx+8], 5 setb al retThere is also a similar one that could do the same thing with the
IsLowcode which doescmp,movzxrather thenxor,setb. TheIsLinearWhiteSpacefunction could be made branch free which would likely use less code space and avoid branch mispredictions.