如何在Zig中实现高效的多ArrayList风格Tagged Union类型?
自定义Zig Tagged Union的MultiArrayList实现需求与问题
我了解Zig的MultiArrayList支持Tagged Union,但它会将其转换为包含无标签union和tag字段的struct,实际会创建两个ArrayList字段——一个用于存储union,另一个用于存储tag。
对于变体较小的场景,这种实现会造成严重的内存浪费。例如:
const TaggedUnion = union(enum) { variant1 : void, variant2 : u8, variant3 : u64, };
无标签union的ArrayList中每个元素会占用8字节空间,如果存在大量variant1或variant2实例,内存浪费问题会非常突出。
自定义实现需求
- 为Tagged Union的每个变体单独创建对应的ArrayList;
- 额外创建一个ArrayList,其中的元素为代表各变体索引的union类型,示例如下:
const TaggedUnion = union(enum) { variant1_index : usize, variant2_index : usize, variant3_index : usize, };
注:如果确定实例数不超过40亿,索引类型可以选择u32;此外部分变体的大小可能远超过8字节。
执行批量操作时,可遍历存储索引Tagged Union的ArrayList,通过switch匹配变体、提取索引后,从对应的ArrayList中获取元素。
方案存在的问题
- 若删除某变体ArrayList中的元素,需遍历整个索引ArrayList,检查元素所属变体并相应递减索引;
- 排序操作难度较大。
已编写的部分代码
fn multi_array_list_tagged_union(T: type) type { // Plan: // 1. Check if T is a tagged union type. // 2. For each field in the tagged union, create an ArrayList. // 3. Create a tagged union type that contains indexes to these ArrayLists. switch (@typeInfo(T)) { .@"union" => |u| { u.tag_type orelse @compileError("Only tagged unions are supported"); }, else => @compileError("Expected a tagged union type"), } // todo 2 and 3 }
内容的提问来源于stack exchange,提问作者Krischal Khanal
相关产品推荐
相关产品推荐

