Skip to content

Instantly share code, notes, and snippets.

@karlseguin
Created February 2, 2025 00:06
Show Gist options
  • Save karlseguin/1d189f683797b0ee00cdb8186f23af98 to your computer and use it in GitHub Desktop.
Save karlseguin/1d189f683797b0ee00cdb8186f23af98 to your computer and use it in GitHub Desktop.
Zig's Writer overhead
const std = @import("std");
const zul = @import("zul");
const Allocator = std.mem.Allocator;
const WriteCtx = struct {
times: u32,
data: []const u8,
expected: []const u8,
arr: std.ArrayList(u8),
};
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
const times = 1000;
const data = "hello world\n";
var arr = std.ArrayList(u8).init(allocator);
try arr.ensureTotalCapacity((data ** times).len);
var wc = WriteCtx{
.arr = arr,
.data = data,
.times = times,
.expected = data ** times,
};
(try zul.benchmark.runC(&wc, genericWriter, .{})).print("genericWriter");
(try zul.benchmark.runC(&wc, appendSlice, .{})).print("appendSlice");
(try zul.benchmark.runC(&wc, appendSliceOptimized, .{})).print("appendSliceOptimized");
}
fn genericWriter(ctx: *WriteCtx, _: Allocator, _: *std.time.Timer) !void {
var arr = &ctx.arr;
arr.clearRetainingCapacity();
try arr.writer().writeBytesNTimes(ctx.data, ctx.times);
if (std.mem.eql(u8, arr.items, ctx.expected) == false) {
@panic("genericWriter");
}
}
fn appendSlice(ctx: *WriteCtx, _: Allocator, _: *std.time.Timer) !void {
var arr = &ctx.arr;
arr.clearRetainingCapacity();
const data = ctx.data;
var i: usize = 0;
const n = ctx.times;
while (i < n) : (i += 1) {
try arr.appendSlice(data);
}
if (std.mem.eql(u8, arr.items, ctx.expected) == false) {
@panic("appendSlice");
}
}
fn appendSliceOptimized(ctx: *WriteCtx, _: Allocator, _: *std.time.Timer) !void {
var arr = &ctx.arr;
arr.clearRetainingCapacity();
const data = ctx.data;
try arr.ensureTotalCapacity(ctx.times * data.len);
var i: usize = 0;
const n = ctx.times;
while (i < n) : (i += 1) {
arr.appendSliceAssumeCapacity(data);
}
if (std.mem.eql(u8, arr.items, ctx.expected) == false) {
@panic("appendSliceOptimized");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment