Like a table, understanding how LUA implements strings allows you to use it more efficiently.
LUA implements strings differently from the two main approaches used by most other scripting languages. First, all the strings in Lua are internally [1], which means that LUA maintains a single copy of any string. When a new string appears, Lua checks for ready-made copies, if any, to reuse them. Internalization makes operations such as string comparisons and index tables very fast, but reduces the speed at which strings are created.
Second, the variables in Lua never store strings, just reference them. This implementation can speed up a lot of string manipulation, for example, in Perl, when you write code similar to the $x= $y, $y is a string, an assignment operation copies the contents of the string from the $y buffer to the $x buffer. If this string is very long, the cost of this operation is very high. In Lua, this assignment is just a copy of a pointer.
However, this reference implementation reduces the speed of string concatenation in a particular way. In Perl, the operation $s = $s. "X" and $s. = "X" is very different, for the former, you get a copy of $s and append "x" to its tail, and for the latter, "X" is simply appended to the tail of the internal buffer that $s maintains. Therefore, the latter has no reference to the length of the string (assuming that the buffer is sufficient to drop the appended text). If you put these two lines into the loop, the difference is between the linear and two-time algorithms. For example, the following loop takes approximately five minutes to read a 5MB file:
Copy Code code as follows:
$x = "";
while (<>)
{
$x = $x. $_;
}
If we put
Copy Code code as follows:
To
Copy Code code as follows:
The time consuming will be reduced to 0.1 seconds!
LUA does not provide a second, faster way, because its variables do not have an internal buffer. So we need an explicit buffer: A table that contains a string fragment to do the job. The following loop reads the same 5MB file, which takes 0.28 seconds, but not as fast as Perl:
Copy Code code as follows:
Local T = {}
For line in Io.lines () do
t[#t + 1] = line
End
s = table.concat (t, "\ n")
[1] internalization, original internalize