Skip to content

Commit

Permalink
writer: Don't grow children array by one each time
Browse files Browse the repository at this point in the history
Each time a child is added we grow by 1, which causes a lot of
reallocs when adding children. Growing capacity by doubling saves us
about 10% of the time of a mkcomposefs --from-image run.

Signed-off-by: Alexander Larsson <[email protected]>
  • Loading branch information
alexlarsson committed Oct 11, 2023
1 parent 85da98b commit 8cd12a1
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
1 change: 1 addition & 0 deletions libcomposefs/lcfs-internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ struct lcfs_node_s {
struct lcfs_node_s *parent;

struct lcfs_node_s **children; /* Owns refs */
size_t children_capacity;
size_t children_size;

/* Used to create hard links. */
Expand Down
28 changes: 17 additions & 11 deletions libcomposefs/lcfs-writer.c
Original file line number Diff line number Diff line change
Expand Up @@ -906,7 +906,7 @@ int lcfs_node_add_child(struct lcfs_node_s *parent, struct lcfs_node_s *child,
const char *name)
{
struct lcfs_node_s **new_children;
size_t new_size;
size_t new_capacity;
char *name_copy;

if ((parent->inode.st_mode & S_IFMT) != S_IFDIR) {
Expand Down Expand Up @@ -936,20 +936,26 @@ int lcfs_node_add_child(struct lcfs_node_s *parent, struct lcfs_node_s *child,
return -1;
}

new_size = parent->children_size + 1;
if (parent->children_capacity == parent->children_size) {
if (parent->children_size == 0)
new_capacity = 16;
else
new_capacity = parent->children_capacity * 2;

new_children = reallocarray(parent->children, sizeof(*parent->children),
new_size);
if (new_children == NULL) {
errno = ENOMEM;
free(name_copy);
return -1;
}
new_children = reallocarray(parent->children,
sizeof(*parent->children), new_capacity);
if (new_children == NULL) {
errno = ENOMEM;
free(name_copy);
return -1;
}

parent->children = new_children;
parent->children = new_children;
parent->children_capacity = new_capacity;
}

parent->children[parent->children_size] = child;
parent->children_size = new_size;
parent->children_size += 1;
child->parent = parent;
child->name = name_copy;

Expand Down

0 comments on commit 8cd12a1

Please sign in to comment.