Tuesday 10 July 2012

Types of simple loops

There are lots of different ways to create loops in Uniface.  Mostly I've found that developers stick to the type they prefer, the one that makes most sense to the way that they think about code.  However, avoiding work in loops is something that is worth considering.  Whenever you have a loop, the conditionality of the loop is run for every iteration, therefore big performance gains can be had by thinking about this conditionality, especially in large loops.  And by large, I mean lots of iterations, not lots of code inside the loop.


So what are the different types of loops...


The while loop is very simple in it's construct.  It just has a condition, which can contain any expression that you wish to put there.  It will be checked at the beginning of each loop, continuing if the condition is true, so if it is never true then the code will never run.  


The repeat loop is also very simple.  It also has a condition, which can contain any expression that you wish.  However, the condition is checked at the end of each loop.  The condition is also reversed; in this case it will loop until it condition true.  This means that if it is true at the start then it will still run the code once.

The for loop has only recently been added to Uniface, in version 9.5.  It has a "counter" variable, a "start" value, an "end" value, and an optional "step" value (which is 1 by default).  This allows you to clearly define the number of times that you wish to loop, right up front.  The condition will be checked at the beginning of each loop, so if the "start" value is never less than the "end" value then the code will never run.


Uniface 9.5 also added some more specific loop commands, but I'll talk about these in a future post.

Having discussed their difference, here is how to make each of them iterate 5 times, and the time it takes to do so 20,000,000 times...


1) while = 00:28.80, 00:28.92, 00:29.01 (about 29 seconds)

  count = 0 
  while ( count < 5 )
    count = count + 1
    ;do something
  endwhile



2) repeat = 00:29.02, 00:29.32, 00:28.93 (about 29 seconds)

  count = 0 
  repeat
    count = count + 1
    ;do something
  until (count >= 5)


3) for = 00:29.05, 00:29.08, 00:29.01 (about 29 seconds)

  for count = 1 to 5
    ;do something
  endfor
  count = count - 1 ;this will equal 6 at the end of the loop



Given the timings, I should probably go back and rewrite my starting paragraph.  But just to prove that I actually write these things as I'm going, I'll do a big U-turn instead :)

Summary: There are different ways of looping in Uniface, but they all perform equally well, so pick your favourite.  Think about the conditionality though, as it will be processed for each iteration.


No comments:

Post a Comment