4.取绝对值时,*-1 比 Math.abs要快.如var test:Number = n < 0 ? n * -1 : n;快于var test:Number = Math.abs(n); 5.n+n比n*2快。 6。Math.sqrt()的替代算法.
function sqrt(w:Number):Number { var thresh:Number = .00001; var b:Number = w * 0.25,a:Number,c:Number; do { c = w / b; b = (b + c) * 0.5; a = b - c; if (a < 0) { a = -a; } } while (a> thresh); return b; } 作者的测试数据表明这个算法比较快一点。
Actual value = 12.136309158883519 Testing threshold: 0.00001 Number of iterations for approximation: 6 Approximation: 12.13630915888352 Error in approximation: 1.7763568394002505e-15 - - - - Math.sqrt - Mean over 20 loops Math.sqrt() Test: 172.05 Approximation Test: 134.8 Empty Test: 4.05 Net timing results: Math.sqrt() Test: 168 Approximation Test: 130.75 可我copy了测试code,在自己电脑测试数据确反应这个算法是慢的。
Actual value = 12.136309158883519 Testing threshold: 0.00001 Number of iterations for approximation: 6 Approximation: 12.13630915888352 Error in approximation: 1.7763568394002505e-15 - - - - Math.sqrt - Mean over 20 loops Math.sqrt() Test: 199.55 Approximation Test: 210.3 Empty Test: 4.9 Net timing results: Math.sqrt() Test: 194.65 Approximation Test: 205.4