KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Optimizing String Assignments
PRODUCT: 4D | VERSION: 20 | PLATFORM: Mac & Win
Published On: July 22, 2024

Assigning string values are one of the first and basic functions in most coding languages. Most people has seen "Hello World!".

4D has various ways to assign string values, but there are some nuances to optimize the performance of string assignments. The main point of optimizing string assignments is to reduce the amount of additional computing required for the assignment.

The first is to reduce the number of operators as possible. Each operator will be its own task and will increase the time it takes to execute the assignment.
For example, instead of the following:

$myText := "Hello"+" "+"World"+"!"
which contains three concatenations and an assignment, the following would perform better:
$myText := "Hellow World!"
which only needs to perform a direct assignment instead of needing to perform any additional operations before the assignment.

Another way to improve string assignments is to reduce the amount of commands and function calls.
For example, instead of adding tabs by adding a call to Char(Tab) it is better to directly assign the literal string equivalent to a tab, "\t".
This will also help reduce the number of concatenations:
$myText:= Char(Tab) + "Hello World!"
vs
$myText:="\tHello World!"

If a computed string is required, in most cases where it will be used multiple times in a process it would be best to assign it to local or process variable:

$myText:= "\t"*$vNumTabs+"Hello World!"

$vTabulation:="\t"*$vNumTabs
...
$myText:=$vTabulation + "Hello World!"

While these suggestions my seem negligible, these optimizations can improve cases where string assignments are performed in loops. The additional overhead for the additional computations and operations can add up for larger loops. The following loop is an extreme example which contains three commands that needs to execute to return a specific character and seven operators.
For ($i; 1; 1000)
   $myText:=Char(Tab)*$vNumTabs+"Hello"+" "+"World"+"!"+Char(Carriage return)+Char(Line feed)
End for

The following has only one concatenation operation:
$vTabulation:="\t"*$vNumTabs
For ($i; 1; 1000)
   $myText:=$vTabulation+"Hello World!\r\n"
End for

To some, these suggestions may be seen as making code harder to read or it may be less flexible, it is up to the development team to pick and choose what best fits the application, and in most cases it's improving the end user experience.