Efficiently determine whether a character value exists in an array (table) in lua

Efficiently determine whether a character value exists in an array (table) in lua

publish: June 28, 2016 -Tuesday by 04007 Original articles on this site, please indicate the source of the article when reprinting: www.04007.cn

    There are very convenient function calls when judging an array in PHP, such as in_array; array_search. But in LUA these wheels need to be built by yourself. There are some common sense methods on the Internet, such as: http://www.jb51.net/article/65457.htm 

Loop through the table, and then judge whether each value corresponds to the value you are looking for. code show as below:

Efficiently determine whether a character value exists in an array (table) in lua

    But this method needs to be looped every time. We know that its complexity is O(n). If there are many strings to be queried, its low efficiency will be more obvious. In fact, we can use the table structure of lua to optimize this kind of query. The table of lua is an efficient table structure, just like we understand the hashtable in PHP. It is only O(1 ), so we can deal with it like this: first perform key-value swap processing on the table to be searched, and then all searches become indexes to the table. If the index value is nil (that is, it is found). The code is as follows :

Efficiently determine whether a character value exists in an array (table) in lua

The statistical results of the execution time of the above code are as follows: multiple tests have shown that the efficiency of the latter method is much higher.

---------- Run Lua ----------
cost time:0.005
cost time:0

output completed (takes 0 seconds) - normal termination

Guess you like

Origin blog.csdn.net/qq_15559109/article/details/110939570