[SOLVED] Performance: Changing the data depending on the options while iterating

Issue

I was writing a personal project and I found myself at a tight spot. To make things easier, code is basically iterating and printing the names of the users. while iterating, I check if getLastName option is enabled, if its True then add it to the final name string. For better understanding, check the code below:

listOfNames = [{ "firstName": "John", "lastName": "David" }, { "firstName": "Bob", "lastName": "Oliver" }]
getLastName = True

for data in listOfNames:
    finalName = data["firstName"]
    if getLastName:
        finalName += f" - {data['lastName']}"
    print(finalName)

Now the problem is, my actual code is pretty complex and checks for many factors (MiddleName, coloredName, …). So, checking each time while iterating is reducing the performance since it checks for many factors and changes the final data. What would be the best approach while keeping the code optimised and good?

If you are confused about what I am trying to achieve, take this code for instance:

# Original data
listOfData = [..., ..., ..., ...]

# Options (or factors)
premiumStatus = True
colored = True
moderator = True
banAble = False

# Iteration
for data in listOfData:
    finalData = ""
    # Changes
    if premiumStatus:
        finalData += "."
    if colored:
        finalData += ".."
    if moderator:
        finalData += "..."
    if banAble:
        finalData += "...."
    print(finalData)

This code obviously is pretty bad because it checks every time for each user for options.

~ Thanks

Solution

First optimization would be to build your string only once, at the end, instead of continually concatenating it:

for data in listOfData:
    finalData = []
    if premiumStatus:
        finalData.append('.')
    ...
    print(''.join(finalData))

If you know the exact format of the listOfData, you can pre-build the template string which you can then format inside the loop:

listOfNames = [{ "firstName": "John", "lastName": "David", "number": 1}, { "firstName": "Bob", "lastName": "Oliver", "number": 2}]
getLastName = True
getFirstName = True
getNumber = False

template_parts = []
if getLastName:
    template_parts.append("{lastName}")
if getFirstName:
    template_parts.append("{firstName}")
if getNumber:
    template_parts.append("{number}")
template_string = " - ".join(template_parts)

for data in listOfNames:
    finalName = template_string.format(**data)
    print(finalName)

Answered By – tmarice

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *