OOJS - Compare Execution Time of Both Approaches


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. var benchmark1;
  2. var benchmark2;
  3. var loop = 1000000
  4. var time
  5.  
  6. // test execution time with approach a
  7. time = new Date().getTime()
  8.  
  9. function ClassA( name )
  10. {
  11. this.name = name
  12. }
  13.  
  14. ClassA.prototype.init = function( index )
  15. {
  16. this.name += index
  17. }
  18.  
  19. for( var i=0;i<loop;i++ )
  20. {
  21. var a = new ClassA( 'A' )
  22. a.init( i )
  23. }
  24.  
  25. benchmark1 = new Date().getTime() - time
  26.  
  27.  
  28. // test execution time with approach b
  29. time = new Date().getTime()
  30.  
  31. function ClassB( name )
  32. {
  33. var o = {}
  34. o.name = name
  35. o.init = com_classb_init
  36. return o
  37. }
  38.  
  39. function com_classb_init( index )
  40. {
  41. this.name += index
  42. }
  43.  
  44. for( var i=0;i<loop;i++ )
  45. {
  46. var b = ClassB( 'B' )
  47. b.init( i )
  48. }
  49.  
  50. benchmark2 = new Date().getTime() - time
  51.  
  52. alert( benchmark1+", "+benchmark2 )

URL: oojs

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.