A Flash Developer Resource Site

Results 1 to 3 of 3

Thread: loops: for, while, do while: just a matter of preference

  1. #1
    Inspector General
    Join Date
    May 2001
    Posts
    493

    loops: for, while, do while: just a matter of preference

    just a quick question.
    I am very comfortable with "for" loops.

    from my understanding they can achieve everything that while and do while can.

    is it just a matter of preference or are the others better for different scenarios?

    i don't find the info on livedocs to highlight much of a difference.

    thanks for your input
    carl

  2. #2
    Senior Member jbum's Avatar
    Join Date
    Feb 2004
    Location
    Los Angeles
    Posts
    2,920
    As you know, for loops are a coding shortcut a while loop that uses an incrementing counter.

    many while loops are structure like so:

    code:

    <setup>
    while (<condition>)
    {
    <increment>
    }

    // for example:

    i = 0;
    while (i < 10)
    {
    i++; // same as i = i + 1
    }



    These tend to work well as for loops.

    code:

    for (<setup>; <condition>; <increment>)
    {
    }

    // for example:
    for (i = 0; i < 10; i++)
    {
    }



    However, there are other cases, where a while loop is sufficient. Especially, if you don't need the setup or increment steps.

    For example:

    code:

    while( functionIsTrue() )
    {
    }



    such as

    code:

    while( ! frozenOver(hell) )
    {
    }



    I tend to use a for loop only if the setup, condition and increment are all simple and involve the same variable. Otherwise, the code is probably easier to read in a while loop.

    If there is a difference in performance, it is quite small and not worth worrying about. Trying to speed up your code? Changes in design and algorithms will give you big gains. Little changes in coding style only give you little gains.
    Last edited by jbum; 10-21-2004 at 01:11 PM.

  3. #3
    Inspector General
    Join Date
    May 2001
    Posts
    493
    thanks so much for your thorough and clear response. I learned something.

    -also a big fan of your work... wow.

    carl

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center