Odd array's capacity Topic is solved

Get help with using AutoHotkey (v2 or newer) and its commands and hotkeys
User avatar
Benny-D
Posts: 305
Joined: 12 Mar 2014, 10:09

Odd array's capacity

Post by Benny-D » 31 Dec 2023, 13:48

Why capacity here is shown as 4? Shouldn't it be 3, instead?

Code: Select all

#Requires AutoHotkey v2.0

SourceCode := "car fence truck fence van"
vehicles := LoadSections(SourceCode)
MsgBox "This many: " . vehicles.Capacity
return

LoadSections(SourceCode)
{
the_array := StrSplit(SourceCode, " fence ")
return the_array
}

coffee
Posts: 133
Joined: 01 Apr 2017, 07:55

Re: Odd array's capacity  Topic is solved

Post by coffee » 31 Dec 2023, 14:11

You shouldn't use the capacity property like that. You need to use "length". vehicles.length, that contains the actual count of items.
Capacity is more of an internal lower abstraction type of thing, that capacity you see is the size the runtime decided to give the array at that point in initialization as a "good enough margin", based on the elements you initialized with it, in order to not have to expand it it later if you add another item. Expanding may be more expensive than preallocating and filling. It decided since you created with 3 items, you probably will not be adding 10 more to it afterwards, but only 1. If you push 1 more item, then capacity == length. You can add more, it will just expand it.
For example, if you know your data set is going to have 1000 elements, it may be faster and easier on the runtime to create an array and make its capacity 1000, array.capacity := 1000, rather than create it empty then push 1000 times into it.
https://www.autohotkey.com/docs/v2/lib/Array.htm#Capacity

User avatar
Benny-D
Posts: 305
Joined: 12 Mar 2014, 10:09

Re: Odd array's capacity

Post by Benny-D » 31 Dec 2023, 14:21

WOW! Thanks for this explanation.

Post Reply

Return to “Ask for Help (v2)”