Should I localize every table method?

I noticed that in a lot of modules, they localize (almost) every table method.

--Example from CanvasDraw

-- Micro optimisations
local TableInsert = table.insert
local TableFind = table.find
local RoundN = math.round
local Vector2New = Vector2.new
local CeilN = math.ceil

Should I do this to every table method? Is it faster this way? Are there some cases where it is slower?

Maybe it used to be useful to avoid looking up the function in _ENV every time, but I don’t think that’s the case anymore with Luau. People did it as a micro optimization, but I do not recommend you pick up on that habit. It’s harder to read and doesn’t make any meaningful difference.

See this section about it on luau’s website: Performance - Luau

It’s always possible to “localize” the global accesses by using local max = math.max, but this is cumbersome - in practice it’s easy to forget to apply this optimization. To avoid relying on programmers remembering to do this, Luau implements a special optimization called “imports”, where most global chains such as math.max are resolved when the script is loaded instead of when the script is executed.

1 Like

No, localizing these won’t affect performance anymore. Many common builtin functions like your examples have been optimized by Luau’s fastcall mechanism, so doing table.insert(t, i) is identical to local insert = table.insert and insert(t, i) in terms of performance. Of course, for readability, the former would be preferable.

See: Performance - Luau

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.