dont fetch the count in loops repeatedly!

This should have been really obvious, but I haven’t really thought about what happens when you do

for(var i =0; i < total(); i++)

with respect to the function total(), which gets called over and over again. If that function has to search through a large document, and total is large, then this could be really inneficient and slow. The right way (obviously) to do this is to assign total() into a variable first, so the code becomes:

var total = total(); 
for (var i=0; i< total; i++) {...}

Here is an example that prints “checking count” 5 times:

    <script type="text/javascript" src="jquery-1.4.2.js"></script>
    <script type="text/javascript">
      function count() {
        $("#log").append("checking count<br>");
        return 5;
      }
      $(function() {
        for (var i=0; i < count(); i++) {
          //do something
        }
      });
    </script>
This entry was posted in Software Development and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">