Lua table, if the key starts from 1000, will there be a performance loss?


I don’t define other things. Will the storage space be occupied from 1 to 999?

I know that a[1]=nil or a[999]=nil, will it be calculated from 1 to 1000 in sequence during traversal?

>Solution :

No, there is not going to be space allocated for other (1-999) elements (unless you create 1000 elements and then delete 1-999). Lua supports "sparse" arrays and will use the hash part of the table to store those key/value pairs.

If you are asking whether a[1000] is going to be slower if 1-999 elements are not present, then it’s possible, as in this case the hash part of the table is going to be used (instead of the array part), but you’ll have to benchmark to see if there is any observable difference that matters in your case.

Leave a Reply