16 July 2012

Efficiently building a String

If you need to build a string by adding lots of pieces together, GFA-BASIC's string handling is relative slow because a new string is created in memory every time a new piece is added.

Often, alternatives are used like string builder functions. String builders allocate a string chunk and then uses memory copy methods to manipulate the data within the same string's memory. You'll find them in all frameworks and libraries of popular programming languages.

GB32 offers an efficient string builder as well, although it is bit hidden. The sprintf() function reserves a chunk of stack memory and uses memory copy functions to copy characters form the source string to a destination string. When it hits on a data placeholder in the source string it copies the data into destination string. Only when all characters and data are copied to destination buffer, the stack buffer in converted to a an actual String.

The difference between the two methods is illustrated below:

Dim sEdPos As String
' Assemble a caret position in a long
Dim EdPos As Long = MakeLong(12, 1)
' Put the string together
sEdPos = "Line: " + Dec(HiWord(EdPos)) + _
  " Column: " + Dec(LoWord(EdPos))
' Or use sprintf()
sEdPos = sprintf("Line: %d Column: %d", _
  HiWord(EdPos), LoWord(EdPos))

No comments:

Post a Comment