Optimization tips?

The first question is, do you actually have a problem? Is the program not fast enough? Remember the three basic requirements of a system: Correct, Robust and Efficient, and the engineering rule of thumb that you may have to pick only two.

Donald Knuth is often quoted about optimisation: "If you optimise everything, you will always be unhappy" and "we should forget about small efficiencies, say about 97% of the time: premature optimisation is the root of all evil."

Assume a program is correct and (hopefully) robust. There is a definite cost in optimising that program, both in programmer time and in code readability. If you don't know what the slow bits are, then you will waste time making your all your program ugly and maybe a little faster (which is why he says you will be unhappy.) So the first step is to use LuaProfiler the program and find the under-performing parts, which will be functions called very often and operations in inner loops. These are the only parts where optimisation is going to give you results, and since typically it is only a small part of the program, you end up doing a fraction of the work, with resulting happiness and less evil committed in terms of ugly code.

There are a few specific Lua tips here. If LuaJIT is available on your system, use that.

The equivalent in Lua of writing inner loops in Assembler is to factor out the heavy CPU-using code, write it as C, and use as an extension module. If done right, you will have a Lua program with almost the performance of a C program, but shorter and easier to maintain.

With LuaJIT you may not need to use C at all, especially since the built-in foreign-function interface FFI makes it very efficient to access external C functions and structures. This can also give more space-efficient representation for arrays of C types, compared to using tables.



Back