From ad436994ba1003eadd8fe623c5bf54b3eafec291 Mon Sep 17 00:00:00 2001 From: Arseny Kapoulkine Date: Tue, 31 Aug 2021 07:28:49 -0700 Subject: [PATCH] Update performance.md (#65) Call out table capacity prediction --- docs/_pages/performance.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/_pages/performance.md b/docs/_pages/performance.md index 076ce61..22352ab 100644 --- a/docs/_pages/performance.md +++ b/docs/_pages/performance.md @@ -102,6 +102,16 @@ Iterating through array-like tables using `for i=1,#t` tends to be slightly slow Luau implements several optimizations for table creation. When creating object-like tables, it's recommended to use table literals (`{ ... }`) and to specify all table fields in the literal in one go instead of assigning fields later; this triggers an optimization inspired by LuaJIT's "table templates" and results in higher performance when creating objects. When creating array-like tables, if the maximum size of the table is known up front, it's recommended to use `table.create` function which can create an empty table with preallocated storage, and optionally fill it with a given value. +When the exact table shape isn't known, Luau compiler can still predict the table capacity required in case the table is initialized with an empty literal (`{}`) and filled with fields subsequently. For example, the following code creates a correctly sized table implicitly: + +```lua +local v = {} +v.x = 1 +v.y = 2 +v.z = 3 +return v +``` + When appending elements to tables, it's recommended to use `table.insert` (which is the fastest method to append an element to a table if the table size is not known). In cases when a table is filled sequentially, however, it's much more efficient to use a known index for insertion - together with preallocating tables using `table.create` this can result in much faster code, for example this is the fastest way to build a table of squares: ```lua