πŸš€ go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.lang.tcl
Article #78

Announce bitarray 1.0 - packed integer arrays for Tcl 9 (C extension)

#78
From: et99
Date: Wed, 21 Oct 2026 19:52
96 lines
8366 bytes

The bitarray C extension stores arrays of small integers (1, 8, 16, 32 or 64 bits, signed or unsigned) packed in memory that looks and behaves like an ordinary Tcl list. To the rest of Tcl a bitarray IS a list: lindex, lset, lrange, lreplace, linsert, foreach, "in", lsort, lsearch, join, {*}$a all work on a bitarrary.

Like any Tcl value, a bitarray needs nothing freed by hand: its memory is allocated from the heap when the array is created and reclaimed automatically when the last reference to it goes away.

It uses the Tcl 9 abstract-list hooks (Tcl_ObjType version 2, the machinery behind lseq).  The result is convenience, lower memory use and better performance.

For example, the code below creates a million 1-bit flags with the bitarray new sub-command and uses lset to change one bit. The fill sub-command then clears every third bit from index 3 to the end, in place, so no new array is allocated. It prints the first and last few elements with lrange, uses next to find the first 0 bit, and uses count to report how many bits are still set out of the array’s length:

     lappend auto_path /path/to/bitarray     ;# path of pkgIndex.tcl and the library
     package require bitarray                ;# returns 1.0

     set flags [bitarray new 1_000_000 1]    ;# a million 1-bit flags: 125 KB vs 8 MB
     lset flags 5 0                          ;# set the bit at index 5 to 0

     # bulk commands run in C combined with regular commands

     bitarray fill flags 3 to end with 0 by 3   ;# to/with/by optional for readabilty
     puts "[lrange $flags 0 10] ... [lrange $flags end-10 end]"
     puts "index [bitarray next $flags 0 with 0] is the first zero bit"
     puts "[bitarray count $flags] on out of [llength $flags]"

output:

1 1 1 0 1 0 0 1 1 0 1 ... 1 0 1 1 0 1 1 0 1 1 0
index 3 is the first zero bit
666666 on out of 1000000


Where the speed is.

Single-element commands (lindex, lset, lappend, llength, foreach) cost about the same as on a list. The gains come from the whole-array commands, which have no plain-list equivalent.

They are implemented using the op sub-command as operators:

     and or xor andnot not land lor lnot    - bitwise
     eq ne lt le gt ge                      - relational (aliases: == != < <= > >=)
     land lor lnot                          - logical    (aliases: && || !)

And other sub-commands:

     count next minmax fill                 - extras

In expr, if, while, for

     in ni                                  - expr operators

They work a 64-bit word at a time, and the logical and relational operators use SSE2 for the 8-, 16- and 32-bit widths on x86-64 (on by default; one build switch turns it off). The table below is one million elements, microseconds per call, measured on Windows with Visual C++ /O2 against the same job done on a plain list with an ordinary Tcl loop. The numbers are from running extras/listbench.tcl on a Windows run.

     operation                         plain list     bitarray    speed-up-approx
     a AND b (1-bit arrays)                87,347          7.9       11,000x
     a AND b (8-bit arrays)                87,347           60        1,450x
     count the 1s (1-bit)                  12,707           20          650x
     minmax of a signed 8-bit array        39,520           30        1,330x
     land of two 8-bit arrays              96,180          153          630x
     lnot of a 16-bit array                50,363          121          415x
     "> 1000" on a 16-bit array           250,769          315          800x

The relational test "> 1000" above is normally used like this:

     set high_bits [bitarray op $flags > 1000]   ;# a new 1-bit array
     bitarray op high_bits = $flags > 1000       ;# slightly faster

     set num [bitarray count $high_bits]         ;# count the 1s

Either of the first two forms gives a 1-bit array of 1s and 0s, the same length as flags, with a 1 wherever the element is greater than 1000. The count of a 1-bit array is a popcount and takes only microseconds per million elements.

The sieve of Eratosthenes, primes to 1,000,000 (Frank van Bakel's entry from Dave's Garage Language Drag Race): 702,000 us as written, 1,180 us with fill and next (~595x). Using only lindex/lset on a bitarray it is about 8x, which is the point: the big gain comes from using the bulk commands.

This is new code for new programs, not a drop-in speed-up of an existing list. Taking a list and swapping in a bitarray while keeping per-element loops gets you the memory saving (64x less for 1-bit, 8x less for 8-bit) and roughly list speed, not these numbers.

And a few things are slower than on a list, because Tcl lists can share storage or reverse in constant time: lreverse, lrange of a large slice (a bitarray copies it), lsearch -exact, and building an array from text. The benchmark (extras/listbench.tcl) times 70 operations side by side and first checks that the list and the bitarray give the same answers; the slow rows are in its output along with the fast ones.

Tcl versions, and one known problem.

It needs the abstract-list hooks, so the target is Tcl 9.1 (trunk, 9.1.1). It also loads and passes all its tests on 9.0.4 (Linux) and 9.0.2 (Windows), with one limitation that is a Tcl core issue, not an extension one: in some places the core converts the bitarray to an ordinary list itself instead of calling the extension's hooks.

The values stay right, but the array becomes a plain list and loses its speed. The cases I know: a plain lappend inside a proc (9.0 and 9.1), lappend under eval and uplevel (9.0 only), and linsert of exactly one element at the end when the command is not compiled (9.0 and 9.1).

The README has a section on Tcl 9.0 with the details, and the test run prints the Tcl version with a warning box when it is older than 9.1.

Testing: 434 tests (428 pass, 6 skipped on 9.1.1; the skipped six are the ones that show the core problem), valgrind of the whole suite with no invalid reads or writes, 98.7% line coverage, and a mutation run of 407 deliberate bugs in the C code with every gap it found closed or explained.

Tested on Linux (gcc) and Windows (Visual Studio 2022). A real 32-bit build has not been tested. Prebuilt Linux x86-64 and Windows x64 libraries are attached to the release, but the one C file builds with ./build.sh or build.bat and that is the safer way.

In the interest of full disclosure: the code, tests and documentation were written by Claude (an AI model from Anthropic), working with me; I directed the work and reviewed it. Because of that, independent review matters, and I would welcome it. The README has a section on reviewing the code, with or without an AI assistant, and there is an interactive page that steps through how the hooks work.

     Release:   https://github.com/rocketship88/tcl-bit-array-extension/releases/tag/v1.0
     Source:    https://github.com/rocketship88/tcl-bit-array-extension
     Stepper:   https://rocketship88.github.io/tcl-bit-array-extension/extras/bitarray_stepper.html

Questions, bug reports and criticism are welcome. Mit Licence.

-Eric
  
Technical Details
Message-ID: <11bb56j$8k4k$1@dont-email.me>
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!.POSTED!not-for-mail

Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!.POSTED!not-for-mail
From: et99 <et99@rocketship1.me>
Newsgroups: comp.lang.tcl
Subject: Announce bitarray 1.0 - packed integer arrays for Tcl 9 (C extension)
Date: Wed, 21 Oct 2026 12:52:50 -0700
Organization: A noiseless patient Spider
Lines: 96
Message-ID: <11bb56j$8k4k$1@dont-email.me>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
Injection-Date: Wed, 21 Oct 2026 19:52:52 +0000 (UTC)
Injection-Info: dont-email.me;
	logging-data="282772"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX19fDeCt656joym28KOciLKy"; posting-host="b50b724fdb106216587008a81b1eecfb"
User-Agent: Mozilla Thunderbird
Cancel-Lock: sha1:EMrbRlw3TnCtNWyZoUa6qwdp0nc= sha256:ijtMTpUSxl7ayxJutbqP9nl7ALHFj94lrxYZmhGtQds=
	sha1:XgTZkG0bLKVpe8Ixrc6mt8Lh2h0= sha256:oX3INTRZMGqjf6vgXT9Sa4bmMWLYIgWe6zQ3Ns24Bks=
Content-Language: en-US