code wiki / _hdl_build / nx_js_objchurn_probe.nx

nx_js_objchurn_probe.nx source

↩ module page · 29 lines · 2190 B

1// diagnose the object-churn gap: is it the CTOR CALL, the property SETs, or obj_new? expect_exit: 0 2// license_tier: ORIGINAL 3import "nx_js_vm.nx" 4func pw(s: *u8) -> i64 { var n: i64 = 0; while s[n] != (0 as u8) { n = n + 1 } sys_write(1, s, n); return 0 } 5func pn(v: i64) -> i64 { if v==0 { sys_write(1,"0" as *u8,1); return 0 } var m: i64=v; if m<0 { sys_write(1,"-" as *u8,1); m=0-m } let t: *u8=sys_mmap(24); var k: i64=0; while m>0 { t[k]=(48+(m%10)) as u8; m=m/10; k=k+1 } let o: *u8=sys_mmap(24); var q: i64=k-1; var x: i64=0; while q>=0 { o[x]=t[q]; x=x+1; q=q-1 } sys_write(1,o,x); return 0 } 6func best3(src: *u8) -> i64 { 7 let out: *i64 = sys_mmap(16) as *i64 8 var best: i64 = 0 9 var r: i64 = 0 10 while r < 3 { let t0: i64 = sys_now_us(); compile_run(src, out); let t1: i64 = sys_now_us(); var us: i64 = t1 - t0; if us < 1 { us = 1 } if r == 0 { best = us } if us < best { best = us } r = r + 1 } 11 return best 12} 13func main(argc: i64, argv: *i64) -> i64 { 14 pw("=== object-churn breakdown (50k iters each) ===\n" as *u8) 15 // A: full new P(x,y) w/ ctor (= h2h K4) 16 let a: i64 = best3("function P(x,y){this.x=x;this.y=y;}var s=0;var i=0;while(i<50000){var p=new P(i,i+1);s=s+p.x+p.y;i=i+1;}s" as *u8) 17 pw(" A new P(x,y) [ctor call + 2 SETPROP + obj_new]: "); pn(a); pw("us\n" as *u8) 18 // B: object LITERAL {x,y} -- NO ctor call, but still 2 prop sets + obj alloc 19 let b: i64 = best3("var s=0;var i=0;while(i<50000){var p={x:i,y:i+1};s=s+p.x+p.y;i=i+1;}s" as *u8) 20 pw(" B {x:i,y:i+1} literal [2 prop set + obj_new, NO ctor call]: "); pn(b); pw("us\n" as *u8) 21 // C: empty new P() -- ctor call + obj_new, NO field sets 22 let c: i64 = best3("function P(){}var s=0;var i=0;while(i<50000){var p=new P();s=s+1;i=i+1;}s" as *u8) 23 pw(" C new P() empty [ctor call + obj_new, NO field sets]: "); pn(c); pw("us\n" as *u8) 24 // D: pure loop baseline (no objects) 25 let d: i64 = best3("var s=0;var i=0;while(i<50000){s=s+i;i=i+1;}s" as *u8) 26 pw(" D pure loop [baseline, no objects]: "); pn(d); pw("us\n" as *u8) 27 pw(" --- INFER: ctor-call cost ~ C-D; prop-set+alloc cost ~ B-D; A vs B = the ctor-call premium ---\n" as *u8) 28 return 0 29}