Advertisement
Guest User

Untitled

a guest
Aug 31st, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3.  
  4. <head>
  5. <title>js test</title>
  6. </head>
  7.  
  8. <body>
  9. <script>
  10. function conditionalLoop(arr) {
  11. var s = null;
  12. if(arr.length === 1) {
  13. s = arr[0];
  14. } else if (arr.length > 1) {
  15. for (var i=0; i<arr.length; i++) {
  16. s = arr[i];
  17. }
  18. }
  19.  
  20. return s;
  21. }
  22.  
  23. function alwaysLoop(arr) {
  24. var s = null;
  25. if (arr.length > 0) {
  26. for (var i=0; i<arr.length; i++) {
  27. s = arr[i];
  28. }
  29. }
  30.  
  31. return s;
  32. }
  33.  
  34. var iterations = 1000000;
  35. console.time('conditionalLoop with one element');
  36. for(var i = 0; i < iterations; i++ ){
  37. conditionalLoop([2]);
  38. };
  39. console.timeEnd('conditionalLoop with one element');
  40.  
  41. console.time('alwaysLoop with one element');
  42. for(var i = 0; i < iterations; i++ ){
  43. alwaysLoop([2]);
  44. };
  45. console.timeEnd('alwaysLoop with one element');
  46.  
  47. console.time('conditionalLoop with two elements');
  48. for(var i = 0; i < iterations; i++ ){
  49. conditionalLoop([2, 3]);
  50. };
  51. console.timeEnd('conditionalLoop with two elements');
  52.  
  53. console.time('alwaysLoop with two elements');
  54. for(var i = 0; i < iterations; i++ ){
  55. alwaysLoop([2, 3]);
  56. };
  57. console.timeEnd('alwaysLoop with two elements');
  58. </script>
  59. </body>
  60.  
  61. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement