20
JAVASCRIPT LOOP Optimization of weak typing [email protected]

JavaScript Loop: Optimization of Weak Typing

Embed Size (px)

Citation preview

2. About
Janlay Wu
x
Gtalk: [email protected]
QQ: 629489
Twitter: @janlay
Blog: janlay.com
5dmedia.com
SunSourcing.com
aabase.com
Re1001.com
Alipay.com
3. i++ vs i--
for(var i = 0, stub = 0; i < 100000; i++) {
stub++;}
for(vari = 100000, stub = 0; i > 0; i--) {
stub++;}
4. Which is faster?
5. Run the code
i--IE 8: 41-55 msChrome 5: 3-7 msFirefox 3: 0-2 msOpera 10: 0-1 ms
i++IE 8: 43-48 msChrome 5: 1-5 msFirefox 3: 0-2 msOpera 10: 0-1 ms
6. Conclusion?
It depends.
7. Why i- is not significantly faster?
Too Young: No warming up
Too Simple: Only one statement
And, depends on JavaScript Compiler
8. Make them more complex
9. 1. Define function for Test cases
var test = function(name, fun, times) {
// validate times
if(times < 1) throw 'Invalid times';
// init
vartimers = [new Date()], count = 0, total = 0;
// run test case
while(count++ < times) {
fun();
timers[count] = new Date();
}
// output result
document.write("

Result for " + name + ":
");
for(vari = 1, interval = 0; i 0; i--) {
stub++; // access variable out of closure
}
}, 10);
test('i++', function() {
for(var i = 0; i < 100000; i++) {
stub++;
}
}, 10);
11. 1,000,000
12. So, we got
i--IE 8: 25.4 msChrome 5: 1.8 msFirefox 3: 0.8 msOpera 10: 2.2 ms
i++IE 8: 27.8 msChrome 5: 0.8 msFirefox 3: 1.0 msOpera 10: 2.0 ms
13. Just ignore the differences
1.0 / 100,000 / 1,000 => 1/100,000,000 (s)
14.
15. Typing!
JavaScript is quite different from Java/C
16. JavaScript is quite different from Java/C
Strong Typing vs Weak Typing
Static Typing vs Dynamic Typing
17. Strong Typing vs Weak Typing
C: short, int, long, float1.0fvs1++ designed for CPU instruction INC++ => INC, -- => DEC> 0 => JNZ (only i--, non-float)< 1 => SUBB, JNC
JavaScript: Number1.0 ~ 1++ inherits from C-style languages++ equals +1, mostly
18. Static Typing vsDynamic Typing
C: types determined in compile timeMay be benefit for optimizationJIT on VM(msvcrt, JVM, .NET)
JavaScript: types determined in run timeBasedon VM, cannot use CPU instructions directly
19. Finally
Consider business logici--: order-independent
Focus on the most important partyou know it
20. Thanks
Q & A