Skip to content

Commit

Permalink
ext: improve fidelity of XML::Document memsize
Browse files Browse the repository at this point in the history
and include test coverage for it
  • Loading branch information
flavorjones committed Mar 4, 2023
1 parent 0804380 commit b026f60
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
10 changes: 9 additions & 1 deletion ext/nokogiri/xml_document.c
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,18 @@ dealloc(void *data)
static size_t
memsize_node(const xmlNodePtr node)
{
/* note we don't count namespace definitions, just going for a good-enough number here */
xmlNodePtr child;
size_t memsize = 0;

memsize += xmlStrlen(node->name);
for (child = (xmlNodePtr)node->properties; child; child = child->next) {
memsize += sizeof(xmlAttr) + memsize_node(child);
}
if (node->type == XML_TEXT_NODE) {
memsize += xmlStrlen(node->content);
}
for (child = node->children; child; child = child->next) {
/* This should count the properties too. */
memsize += sizeof(xmlNode) + memsize_node(child);
}
return memsize;
Expand Down
44 changes: 44 additions & 0 deletions test/test_memory_leak.rb
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,50 @@ def test_leaking_dtd_nodes_after_internal_subset_removal
end
end # if NOKOGIRI_GC

def test_object_space_memsize_of
begin
require "objspace"
rescue LoadError
skip("ObjectSpace not available")
end

base_size = ObjectSpace.memsize_of(Nokogiri::XML(<<~XML))
<root>
<child>asdf</child>
</root>
XML

more_children_size = ObjectSpace.memsize_of(Nokogiri::XML(<<~XML))
<root>
<child>asdf</child>
<child>asdf</child>
<child>asdf</child>
</root>
XML
assert(more_children_size > base_size, "adding children should increase memsize")

attributes_size = ObjectSpace.memsize_of(Nokogiri::XML(<<~XML))
<root>
<child a="b" c="d">asdf</child>
</root>
XML
assert(attributes_size > base_size, "adding attributes should increase memsize")

string_size = ObjectSpace.memsize_of(Nokogiri::XML(<<~XML))
<root>
<child>asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf</child>
</root>
XML
assert(string_size > base_size, "longer strings should increase memsize")

bigger_name_size = ObjectSpace.memsize_of(Nokogiri::XML(<<~XML))
<root>
<superduperamazingchild>asdf</superduperamazingchild>
</root>
XML
assert(bigger_name_size > base_size, "longer tags should increase memsize")
end

module MemInfo
# from https://stackoverflow.com/questions/7220896/get-current-ruby-process-memory-usage
# this is only going to work on linux
Expand Down

0 comments on commit b026f60

Please sign in to comment.