Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9122509
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T06:07:14+00:00 2026-06-17T06:07:14+00:00

I’m currently supporting a legacy python application that generates all the html through creating

  • 0

I’m currently supporting a legacy python application that generates all the html through creating individual tag objects.

We have a parent TAG class

class TAG(object):
    def __init__(self, tag="TAG", contents=None, **attributes):
        self.tag = tag
        self.contents = contents
        self.attributes = attributes

So every other tag inherits from TAG

class H1(TAG):
    def __init__(self, contents=None, **attributes):
        TAG.__init__(self, 'H1', contents, **attributes)
class H2(TAG):
    def __init__(self, contents=None, **attributes):
        TAG.__init__(self, 'H2', contents, **attributes)

The main TAG class has a to_string method that’s something along the lines of

def to_string(self):
    yield '<{}'.format(self.tag)
    for (a, v) in self.attr_g():
        yield ' {}="{}"'.format(a, v)
    if self.NO_CONTENTS:
        yield '/>'
    else :
        yield '>'
        for c in self.contents:
            if isinstance(c, TAG):
                for i in c.str_g():
                    yield i
            else:
                yield c
        yield '</{}>'.format(self.tag)

We basically write out the result of the to_string method.

The issue comes to pages where there’s a lot of TAGS being generated and is big enough to create a performance hit.

Are there any quick wins that I can do to make it perform better?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T06:07:15+00:00Added an answer on June 17, 2026 at 6:07 am

    Preface: This is a terrible way to generate HTML, but if you’re going to do it, you’d might as well do it the best way possible.

    One thing that python is exceptionally good at is string formatting. If you’re concatting lots of tiny strings, you’re killing your performance from the get-go. Your to_string() method should look more like this:

    def to_string(self):
        return """<{tag}{attributes}>{content}</{tag}>""".format(
            tag=self.tag,
            attributes=' '.join('%s="%s"' % (attr, val) for
                                attr, val in self.attributes),
            content=''.join(
                (n if isinstance(n, basestring) else n.to_string()) for
                n in self.contents))
    

    Take note of a few things that I did there:

    1. This is Python, not Java. Stack frames are expensive, so minimize function and method calls.
    2. If you don’t need a function to abstract a property, don’t do it. I.e.: you don’t need attr_g (except maybe to do escaping, but you can do that when you’re putting the data in instead).
    3. Do all of your string formatting on the same string! Having a single string formatting operation for a tiny string and then yielding it to be concatted is a huge waste.
    4. Don’t use a generator for this. Every time you yield, you’re mussing around with the instruction pointer, which is going to inherently slow things down.

    Other pointers:

    • You’re inheriting from object, so use the super() function.
    • Don’t waste code by writing constructors to declare the tag type:

      class TAG(object):
          def __init__(self, contents=None, **attributes):
              self.contents = contents
              self.attributes = attributes
      
      class H1(TAG):
          tag = 'H1'
      
      class H2(TAG):
          tag = 'H2'
      
    • You might have some success with StringIO objects if you’re doing a lot of this. They’ll let you build your tags and .write() them in. You can think of them as .Net StringBuffers or Java’s StringBuilders.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want use html5's new tag to play a wav file (currently only supported
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I'm working with an upstream system that sometimes sends me text destined for HTML/XML
Let's say I'm outputting a post title and in our database, it's Hello Y&#8217;all
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I've got a string that has curly quotes in it. I'd like to replace
I have a small JavaScript validation script that validates inputs based on Regex. I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.