The classic Win32 list box control lets you preallocate memory in anticipation of adding a large number of items. The documentation recommends doing this for cases where you are adding more than 100 items to a list box.¹ What is being preallocated here?
The list box internally tracks the items as an array of structures and a separate memory pool for strings. What LB_ does is tell the list box control to preallocate memory for the two blocks: Make the first memory block big enough that you can add at least wParam items to the list box, and grow the second memory block so that it can hold an additional lParam bytes of string data.
The number of bytes required to hold a string includes a null terminator, so a 12-character Unicode string requires (12 + 1) × 2 = 26 bytes. Therefore, if you intend to have a total of 100 Unicode strings, each an average of 10 characters long, you would recommend expanding the string memory pool by 100 × (10 + 1) × 2 = 2200 bytes. The call to LB_ would be
SendMessage(hwndLB, LB_INITSTORAGE, 100, 100 * (10 + 1) * sizeof(TCHAR));
Preallocating the memory avoids quadratic memory allocation behavior when the buffers have to be grown each time a new item is added.²
¹ Personally, I think that 100 items is too many for a list box, from a usability standpoint. If you have that many items, I think an auto-suggest box is a better choice, so that people can just type a partial string to narrow the search rather than being forced to scroll through multiple pages to get to the item they want.
² Note however that quadratic behavior is not avoided completely. Internally, that array of structures is really a series of parallel arrays packed together, so adding an item requires that all the items in the second and subsequent parallel arrays be moved to make room for the new item in the first array. Another reason not to have a large number of items in your list box.
0 comments
Be the first to start the discussion.