Use LUA local variables to optimize performance while comparing local variables and global variables

Source: Internet
Author: User


In a highly competitive gaming industry, using scripting can reduce difficulty and cost, especially in the face of challenging and frequent requests for page tours. In the process of using LUA, global variables are frequently accessed as configuration files.

When accessing global variables, you can use local variables to refer to global variables for optimization. Of course, such optimizations have no meaning.

Locals Vs Globals from Http://lua-users.org/wiki/LocalsVsGlobals




Comparison between local and global variables:


Implementation:locals index An array of registers on the stack, with hard-coded integer index (at least in the Mplementation--luaimplementations).
Globals index from a table (or UserData), typically with variable name string, stored as constant or variable, as the key.
Implementation: In the LUA standard implementation, use the Hard-code Integer index to index local variables on the registers on the stack.
In table or UserData, global variables are indexed by string constants or string variables as keys.
Performance:the above point implies this locals can be a bit faster
Still, table indexing is a fairly efficient operation in Lua (e.g. strings was interned with precomputed hash), so this PO int can often be ignored unless profiling indicates optimization are needed.
Performance: By implementing different, local variables are slightly faster than global variables. However, indexing by string in Lua table is also fairly fast. Because the string is instantiated in Lua, the hash value is calculated beforehand.
Therefore, performance problems can be ignored unless you are profiling optimization performance.
Syntax:if an environment table was set, globals can be accessed in Lua code with or without explicitly naming the ENVIRONM ENT table They come from:foo, _g.foo, or getfenv (). foo (or in 5.2.0work3, _env.foo).
This allows different styles of environment usage, such as in Moduledefinition.
Syntax: If the Environment table is a collection, the global variable can be obtained by Foo,_g.foo or getfenv (). Foo outside of the environment table.
However, local variables can only be obtained in the module definition.
Scope:locals is scoped within a lexical block. Globals is scoped within any number of functions assigned a given environment table at Run-time.
Scope: The scope of the local variable is in the syntax block. At run time, global variables can be obtained from functions in any environment table assignment.
Declaration:locals must is explicitly declared, with the local statement, to use them.
Globals can accessed on-the-fly, even with variable name set at runtime
The list of locals is defined statically. The list of Globals May is determined at run-time and can even change during program execution.
Declaration: Local variables must be defined and used by explicit declarations. All declarations of local variables are static. However, global variables can be accessed dynamically at code execution time, and even global variables can be set at run time.
All global variables can be determined at run time and set to change global variables during code execution.
Standard library access:the The library is normally exposed to a chunk via globals.
Access to the standard library: all LUA standard libraries are exposed to the consumer through global variables.
Precedence:locals override Globals.
Precedence: Local variables override global variables
Bytecode introspection:globals is more visible in the bytecode.
Global Get/sets become Getglobal/setglobal opcodes with the given variable name.
It is possible to list all the globals read or written byte a compiled chunk.
Limit on number:there are a limit to the number of locals per function (maxlocals, typically 200).
BYTE code introspection:
Global variables are visible in bytecode. By setting the variable name, gets or sets the global variable into the GETGLOBAL/SETGLOBAL directive.
All global variables can be listed by reading or writing a precompiled block.
Quantity limit:
In each function, the maximum number of local variables is 200.


Basic Facts from Lua performance Tips Roberto Ierusalimschy
Before running any code, Lua translates (precompiles) The source to an internal format.
This format is a sequence of instructions for a virtual machine, similar to machine code for a real CPU.
This internal format was then interpreted by C code that was essentially a while loop with a large switch inside, one case f or each instruction.
Lua pre-compiles the source code into an internal bytecode format before running any code.
The bytecode format is the serialization of the virtual machine specified, similar to the actual CPU of the machine instruction. Internal bytecode format The interpreter written in C is continuously executing a switch for each specified by a basic while loop.
Perhaps you has already read somewhere, since version 5.0, Lua uses a register-based virtual machine.
The "registers" of this virtual machine does not correspond to real registers in the CPU, because this correspondence would Be is not portable and quite limited in the number of registers available.
Instead, Lua uses a stack (implemented as an array plus some indices) to accommodate its registers.
Each of the active function has a activation record, which is a stack slice where in the function stores its registers.
So, each function have its own registers2.
Each function is a registers, because each instruction have only 8 bits to refer to a register.
Since version 5.0, LUA has used a register-based virtual machine VM. The "registers" does not depend on the CPU's true instructions, and the registers due to the registers limit will cause Lua to not be ported.
Instead, LUA uses a stack to solve registers. Each function has a maximum of 250 registers, because each one specifies only 8 to execute the register.
Given that large number of registers, the Lua Precompiler are able to store all local variables in registers.
The result is this access to local variables are very fast in Lua.
So, it's easy-to-justify one of the most important rules to improve the performance of Lua Programs:use locals!
Dependent on a large number of Registers,lua can be precompiled so the local variable is in registers. Therefore, accessing local variables in Lua is very fast. Therefore, a very important principle when optimizing LUA performance is to use local variables: local variables.
If you need to squeeze performance out of your program, there is several
Places where can use locals besides the obvious ones.
For instance, if a function within a long loop, you can assign the function to a local variable. For instance, the code
For i = 1, 1000000 do
Local x = Math.sin (i)
End
Runs 30% slower than this one:
Local sin = Math.sin
For i = 1, 1000000 do
Local x = sin (i)
End

Test code:

Module.lua file:

A =1
B =1

Main.lua file:

Print ("=================================")
Require ("module")
Local A =a
Local T1 =os.clock ()


For i=1,100000000 do
A =2
End


Local T2 =os.clock ()


Print ("To optimize access to global variables by local variables:"). (T2-T1))




Local T1 =os.clock ()


For i=1,100000000 do
B =2
End


Local T2 =os.clock ()
Print ("Direct access to global variables:"). (T2-T1))
Print ("=================================")


Local T1 =os.clock ()
Local sin = Math.sin
For i = 1, 100000000 do
Local x = sin (i)
End
Local T2 =os.clock ()
Print ("To optimize access to global variables by local variables:"). (T2-T1))
Local T1=os.clock ()
For i=1,100000000 do
x = Math.sin (i)
End
Local T2 =os.clock ()
Print ("Direct access to global variables:"). (T2-T1))

Test results:

=================================
To optimize access to global variables by local variables: 0.825
Direct access to global variables: 1.961
=================================
To optimize access to global variables by local variables: 7.017
Direct access to global variables: 10.264

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Use LUA local variables to optimize performance while comparing local variables and global variables

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.