Tech Tip: Commands to Improve Efficiency of Code
PRODUCT: 4D | VERSION: 19 R4 | PLATFORM: Mac & Win
Published On: March 28, 2022
4D v19 R4 introduces some new commands that provide improved controls over loops and the efficiency of code. The new commands introduced are return, break, and continue.
In versions prior, loop control would have to be self implemented to improve the efficiency of the code. For example, a for loop used to search 100 items for an exact value would run 100 times regardless of where the item was located unless code was added to update the iterator meaning the iterator cannot be used for other parts of the logic:
For ($iterator, 1, 100) If($myArray{$iterator} = 50) $found:=True //Need to add the following to stop the loop early //$iterator = 100 End if End for |
With the new commands, the loop can be escaped without modifying the iterator allowing for the iterator to be used for other things:
For ($iterator, 1, 100) If($myArray{$iterator} = 50) $found:=True break End if End for ALERT("50 is at position" + String($iterator)) |
The other command return, allows the method to imediately stop and return the parameter passed. In the following example, all code that should logically be executed up until the return line is performed. When the return line is executed, the method completes and returns "Hello World".
//...some code return("Hello World") //...alot more code, which is not executed |
The last command is the continue command. This command allows the current iteration of a loop to be skiped and continue with the next iteration. For example, a print needs to be created for all 50 employees except for "Bob":
For($i; 1; 50) If($employeeNames{$i} = "Bob") continue End if //...Print handout End for |
Utilizing these commands will allow code to be more efficient allowing methods and loops to stop executing code that does not need to be run and speeding up proceedures.