Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <title>js test</title>
- </head>
- <body>
- <script>
- function conditionalLoop(arr) {
- var s = null;
- if(arr.length === 1) {
- s = arr[0];
- } else if (arr.length > 1) {
- for (var i=0; i<arr.length; i++) {
- s = arr[i];
- }
- }
- return s;
- }
- function alwaysLoop(arr) {
- var s = null;
- if (arr.length > 0) {
- for (var i=0; i<arr.length; i++) {
- s = arr[i];
- }
- }
- return s;
- }
- var iterations = 1000000;
- console.time('conditionalLoop with one element');
- for(var i = 0; i < iterations; i++ ){
- conditionalLoop([2]);
- };
- console.timeEnd('conditionalLoop with one element');
- console.time('alwaysLoop with one element');
- for(var i = 0; i < iterations; i++ ){
- alwaysLoop([2]);
- };
- console.timeEnd('alwaysLoop with one element');
- console.time('conditionalLoop with two elements');
- for(var i = 0; i < iterations; i++ ){
- conditionalLoop([2, 3]);
- };
- console.timeEnd('conditionalLoop with two elements');
- console.time('alwaysLoop with two elements');
- for(var i = 0; i < iterations; i++ ){
- alwaysLoop([2, 3]);
- };
- console.timeEnd('alwaysLoop with two elements');
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement