Concatenating

The letters ABC concatenated with XYZ would be simply ABCXYZ. How hard could this be for a computer? Pretty hard, we will see.

Syntax

Some languages distinguish between characters and strings. These often provide a mechanism different than concatenation to add a character to a string.

Some languages provide a binary operator to concatenate strings. A || B or A + B could mean concatenation. The latter leads to much confusion when variables are also converted freely between strings and numbers.

Some languages provide functions to concatenate strings. strcat(dest, src) concatenates src to dest and returns dest. strcatn is a safer variation that sets a limit to the size of the result.

Some languages provide string literals with variables or expressions interpolated into the final value. "$a and $b" would expand to "jelly and jam" if variables $a and $b were so defined. "Attending: #{attendees.join(', ')}." might expand to "Attending: Tom, Dick, Harry." if the array attendees contained those names.

Concatenation might apply to arrays of any object as well as strings of characters. Concatenation might be inherited from SequenceableCollection or some other superclass.

Memory

The most persistent challenge is to find space for the result. We will need at least room for n+m letters if we concatenate an n letter string with an m letter string. That room has to come from somewhere.

Try concatenating a string to itself 20 times. Try 30, 40.

Some languages make allocating space for strings a programmer responsibility. One would create a buffer for a string and then put strings into the buffer concatenating as one goes. Too many strings leads to a buffer overrun which may be caught as an error or simply continue until something strange or wonderful happens.

Some languages allocate space for strings automatically. Although convenient, careless use of this feature can set the computer working very hard.

When strings are used and forgotten the language must eventually find them to recover the space for new strings. We may notice the computer pause for garbage collection.

When strings are used and not forgotten the language must find ever increasing space, usually from the operating system, often distracting it from other useful work. The operating system might start using disk space reading and writing it to try to keep the program running. The disk becomes virtual memory. With no clear reason to stop, the computer remains busy, perhaps too busy to notice that the user wants to do something else.