4 ms·
> In order to statically compile a very highly dynamic language, you really do need to do some static analysis to eliminate some of the dynamism. Or you can re
by pg314 10y ago
> In order to statically compile a very highly dynamic language, you really do need to do some static analysis to eliminate some of the dynamism.
Or you can require the user to add type annotations, if/when he wants fast code.
In SBCL (a compiler for Common Lisp):
(defun count-even (array)
(declare (optimize speed (safety 0))) ; <- these are the optimisation settings for this function
(declare ((simple-array fixnum) array)) ; <- the argument to the function is an array of fixed sized integers
(loop for x across array count (evenp x)))
This compiles down to quite efficient assembly:
> (disassemble 'count-even)
; disassembly for COUNT-EVEN
; Size: 65 bytes
; 05A7ABC2: BB17001020 MOV EBX, 537919511 ; no-arg-parsing entry point
; BC7: 498BF8 MOV RDI, R8
; BCA: 31C9 XOR ECX, ECX
; BCC: 31F6 XOR ESI, ESI
; BCE: 31D2 XOR EDX, EDX
; BD0: 498B70F9 MOV RSI, [R8-7]
; BD4: 660F1F840000000000 NOP
; BDD: 0F1F00 NOP
; BE0: L0: 4839F1 CMP RCX, RSI
; BE3: 7D18 JNL L1
; BE5: 488B5C8F01 MOV RBX, [RDI+RCX*4+1]
; BEA: 4883C102 ADD RCX, 2
; BEE: 4883E302 AND RBX, 2
; BF2: 4885DB TEST RBX, RBX
; BF5: 75E9 JNE L0
; BF7: 4883C202 ADD RDX, 2
; BFB: EBE3 JMP L0
; BFD: L1: 488BE5 MOV RSP, RBP
; C00: F8 CLC
; C01: 5D POP RBP
; C02: C3 RET
If you don't add the type annotation (the second declare form), the compiler will tell you that it can't optimise the code because of type uncertainty. Optimising a program becomes a dialogue between the user and the compiler.
- int_19h 10y agoThe entire second half of the comment you've replied to addresses this approach at great length.