Thursday, January 24, 2013

Scripting: Better String Concatenation

Better String Concatenation

Note: This tutorial is for users who already have a basic understanding of Lua in general.

Introduction

First off, what is "string concatenation?"  String concatenation is simply the joining of two strings. For example, local str = "Hello" .. "World" There we combined Hello and World together through concatenation.

The Big Issue

String concatenation is great, however, there is a looming issue that is faced within just about any programming language: Repetitive additions to a string through concatenation is very performance-costly. For example, if you want to add "Hello" 100,000 times to a single string variable, using standard loops with standard concatenation is going to create a performance issue.

Example of the above scenario using default string concatenation in Lua:

local str = ""

for i = 1,100000 do
   str = str .. "Hello"
end

The above code took 4700 milliseconds (4.7 seconds) to execute completely.


The Better Method

Thankfully, there is a much better way to accomplish the same task in much less time. In some languages, such as Java, you have things like the java StringBuilder object, which fixes this whole mess of performance issues by appending strings and then shoving them all together when you need them.

In Lua, we can devise our own method by using tables and table.concat. In fact, the method of going about doing this is quite simple too. Instead of constantly concatenating our 'str' variable with "Hello," we are going to add "Hello" to a table. At the end of the loop, we will concatenate the table into a readable string variable. This is much quicker.

Example of the better method using tables and table concatenation:


local str = ""
local strHold = {} -- Table to hold string data

for i = 1,100000 do
   table.insert(strHold, "Hello")
end

str = table.concat(strHold)

The above code took 60 milliseconds (0.06 seconds) to execute completely. As you can see, there was a tremendous increase in performance speed.


A Final Note

As a final note, I would like to tell you that standard concatenation is NOT BAD. The method shown in this tutorial should only be used when needing to concatenate a large string object multiple (thousands of) times as quickly as possible. On Roblox, there will be few times when you will need to use this method, however it is an extremely valuable skill to know in the real world of programming.

No comments:

Post a Comment