Skip to content

Commit d959592

Browse files
committed
Be smarter about freeing/reallocating content buffers in Nodes.
If the buffer is already big enough to store the string that we want to store in it, no need to free/reallocate; just use the buffer we already have.
1 parent d49be80 commit d959592

2 files changed

Lines changed: 16 additions & 8 deletions

File tree

Changes

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ Revision history for Perl extension JavaScript::Minifier::XS.
22

33
{{$NEXT}}
44
- rewrote test suite into a single ".t" test
5-
- optimized memory allocations, by allocating Nodes in bulk
5+
- optimized memory allocations, by allocating Nodes in bulk, and being
6+
smarter about when we need to free/reallocate content buffers in Nodes
67

78
0.13 2020-12-30 21:46:29-08:00 America/Vancouver
89
- POD cleanups; spelling, SYNOPSIS

XS.xs

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -247,13 +247,20 @@ void JsClearNodeContents(Node* node) {
247247

248248
/* sets the contents of a node */
249249
void JsSetNodeContents(Node* node, const char* string, size_t len) {
250-
size_t bufSize = len + 1;
251-
/* clear node, set new length */
252-
JsClearNodeContents(node);
253-
node->length = len;
254-
/* allocate string, fill with NULLs, and copy */
255-
Newz(0, node->contents, bufSize, char);
256-
strncpy( node->contents, string, len );
250+
/* if the buffer is already big enough, just overwrite it */
251+
if (node->length >= len) {
252+
memcpy( node->contents, string, len );
253+
node->contents[len] = '\0';
254+
node->length = len;
255+
}
256+
/* otherwise free the buffer, allocate a new one, and copy it in */
257+
else {
258+
JsClearNodeContents(node);
259+
node->length = len;
260+
/* allocate string, fill with NULLs, and copy */
261+
Newz(0, node->contents, (len+1), char);
262+
memcpy( node->contents, string, len );
263+
}
257264
}
258265

259266
/* removes the node from the list and discards it entirely */

0 commit comments

Comments
 (0)