Skip to content

Commit

Permalink
Avoid duplicating the entire string when writing
Browse files Browse the repository at this point in the history
With a very large file, we avoid duplicating the whole string just to add the wrapper at the begging then at the end.

I think this should save a lot on memory allocations and garbage collections on large sitemaps.
  • Loading branch information
czj committed Jan 2, 2025
1 parent c81b055 commit 024273e
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 6 deletions.
9 changes: 5 additions & 4 deletions lib/sitemap_generator/builder/sitemap_file.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ def initialize(opts={})
@location = opts.is_a?(Hash) ? SitemapGenerator::SitemapLocation.new(opts) : opts
@link_count = 0
@news_count = 0
@xml_content = String.new # XML urlset content
@xml_wrapper_start = <<-HTML
<?xml version="1.0" encoding="UTF-8"?>
<urlset
Expand All @@ -43,8 +42,9 @@ def initialize(opts={})
>
HTML
@xml_wrapper_start.gsub!(/\s+/, ' ').gsub!(/ *> */, '>').strip!
@xml_wrapper_end = %q[</urlset>]
@xml_wrapper_end = '</urlset>'
@filesize = SitemapGenerator::Utilities.bytesize(@xml_wrapper_start) + SitemapGenerator::Utilities.bytesize(@xml_wrapper_end)
@xml_content = @xml_wrapper_start
@written = false
@reserved_name = nil # holds the name reserved from the namer
@frozen = false # rather than actually freeze, use this boolean
Expand Down Expand Up @@ -138,8 +138,9 @@ def write
raise SitemapGenerator::SitemapError.new("Sitemap already written!") if written?
finalize! unless finalized?
reserve_name
@location.write("#{@xml_wrapper_start}#{@xml_content}#{@xml_wrapper_end}", link_count)
@xml_content = @xml_wrapper_start = @xml_wrapper_end = String.new
@xml_content << @xml_wrapper_end
@location.write(@xml_content, link_count)
@xml_content = @xml_wrapper_end = ''
@written = true
end

Expand Down
4 changes: 2 additions & 2 deletions lib/sitemap_generator/builder/sitemap_index_file.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ def initialize(opts={})
@location = opts.is_a?(Hash) ? SitemapGenerator::SitemapIndexLocation.new(opts) : opts
@link_count = 0
@sitemaps_link_count = 0
@xml_content = +'' # XML urlset content
@xml_wrapper_start = +<<-HTML
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex
Expand All @@ -23,8 +22,9 @@ def initialize(opts={})
>
HTML
@xml_wrapper_start.gsub!(/\s+/, ' ').gsub!(/ *> */, '>').strip!
@xml_wrapper_end = %q[</sitemapindex>]
@xml_wrapper_end = '</sitemapindex>'
@filesize = SitemapGenerator::Utilities.bytesize(@xml_wrapper_start) + SitemapGenerator::Utilities.bytesize(@xml_wrapper_end)
@xml_content = @xml_wrapper_start
@written = false
@reserved_name = nil # holds the name reserved from the namer
@frozen = false # rather than actually freeze, use this boolean
Expand Down

0 comments on commit 024273e

Please sign in to comment.