From 23589360cd3ce4759a1f6f9ae9fabadbcda8e834 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=ED=98=95=EA=B7=BC=20=28Nomota=20Hiongun=20KIM=29?= Date: Fri, 7 Jul 2023 13:18:06 +0900 Subject: [PATCH] binarytrees/1.zig Node allocator Assigning allocator to every Node object is absurd. Make it static, so that set only once. --- bench/algorithm/binarytrees/1.zig | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/bench/algorithm/binarytrees/1.zig b/bench/algorithm/binarytrees/1.zig index 1f1a0bee8..76c96e1b1 100644 --- a/bench/algorithm/binarytrees/1.zig +++ b/bench/algorithm/binarytrees/1.zig @@ -1,6 +1,4 @@ const std = @import("std"); -const builtin = @import("builtin"); -const math = std.math; const Allocator = std.mem.Allocator; const MIN_DEPTH = 4; @@ -9,14 +7,15 @@ const global_allocator = std.heap.c_allocator; pub fn main() !void { const stdout = std.io.getStdOut().writer(); const n = try get_n(); - const max_depth = math.max(MIN_DEPTH + 2, n); + const max_depth: usize = @max(MIN_DEPTH + 2, n); + Node.init(global_allocator); { const stretch_depth = max_depth + 1; - const stretch_tree = Node.make(stretch_depth, global_allocator).?; + const stretch_tree = Node.make(stretch_depth).?; defer stretch_tree.deinit(); try stdout.print("stretch tree of depth {d}\t check: {d}\n", .{ stretch_depth, stretch_tree.check() }); } - const long_lived_tree = Node.make(max_depth, global_allocator).?; + const long_lived_tree = Node.make(max_depth).?; defer long_lived_tree.deinit(); var depth: usize = MIN_DEPTH; @@ -25,7 +24,7 @@ pub fn main() !void { var sum: usize = 0; var i: usize = 0; while (i < iterations) : (i += 1) { - const tree = Node.make(depth, global_allocator).?; + const tree = Node.make(depth).?; defer tree.deinit(); sum += tree.check(); } @@ -45,15 +44,13 @@ fn get_n() !usize { const Node = struct { const Self = @This(); - allocator: Allocator, + var allocator: Allocator = undefined; left: ?*Self = null, right: ?*Self = null, - pub fn init(allocator: Allocator) !*Self { - var node = try allocator.create(Self); - node.* = .{ .allocator = allocator }; - return node; + pub fn init(alloc: Allocator) void { + Self.allocator = alloc; } pub fn deinit(self: *Self) void { @@ -63,15 +60,15 @@ const Node = struct { if (self.right != null) { self.right.?.deinit(); } - self.allocator.destroy(self); + allocator.destroy(self); } - pub fn make(depth: usize, allocator: Allocator) ?*Self { - var node = Self.init(allocator) catch return null; + pub fn make(depth: usize) ?*Self { + var node = allocator.create(Node) catch return null; + node.* = .{ }; if (depth > 0) { - const d = depth - 1; - node.left = Self.make(d, allocator); - node.right = Self.make(d, allocator); + node.left = Self.make(depth-1); + node.right = Self.make(depth-1); } return node; }