Skip to content

Commit b1381d3

Browse files
Merge pull request #403 from jvanvugt/joris/use-stackbuffer-for-ptsort
Avoid malloc overhead for small arrays in ptsort
2 parents 3c97a99 + f10450e commit b1381d3

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

apriltag_quad_thresh.c

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -714,8 +714,16 @@ static inline void ptsort(struct pt *pts, int sz)
714714
#undef MAYBE_SWAP
715715

716716
// a merge sort with temp storage.
717-
718-
struct pt *tmp = malloc(sizeof(struct pt) * sz);
717+
// Use stack allocation for small arrays to avoid malloc overhead
718+
#define STACK_BUFFER_SIZE 256
719+
struct pt stack_buffer[STACK_BUFFER_SIZE];
720+
struct pt *tmp;
721+
const bool use_heap = sz > STACK_BUFFER_SIZE;
722+
if (use_heap) {
723+
tmp = malloc(sizeof(struct pt) * sz);
724+
} else {
725+
tmp = stack_buffer;
726+
}
719727

720728
memcpy(tmp, pts, sizeof(struct pt) * sz);
721729

@@ -749,7 +757,9 @@ static inline void ptsort(struct pt *pts, int sz)
749757
if (bpos < bsz)
750758
memcpy(&pts[outpos], &bs[bpos], (bsz-bpos)*sizeof(struct pt));
751759

752-
free(tmp);
760+
if (use_heap) {
761+
free(tmp);
762+
}
753763

754764
#undef MERGE
755765
}

0 commit comments

Comments
 (0)