Peter Force
Peter Force

Reputation: 449

Most computationally efficient way to prevent appending to string if appending variable is `None`

I am going through a JSON tree and appending particular values to a string.

Occasionally, the JSON object returns None and my code gives an error because Python does not allow appending None to a string.

In this case, what is the most computationally efficient way to prevent appending anything ? I will be going over hundreds of Millions of strings to speed is very important.

The most common solution I have found is to use filter(None, yourList) but that will not work for my case because I am going through different JSON objects with different tree structures and searching and extracting only certain values.

I am going through millions of JSON objects so speed and computational efficiency are more important than compactness of code, if that is a factor.

So in a nutshell

a = None

b = 'this string' + somefunction(a)

print(b)

this string

This is the best I could come up with

def somefunction(strr):
    if strr == None:
        return ''
    else: 
        return strr

But I am wondering if this is the fastest solution. Since I am going through hundreds of millions of objects, any speed up will be very beneficial.

Upvotes: 0

Views: 305

Answers (1)

vurmux
vurmux

Reputation: 10030

You can convert a to '' if it is equal to None:

a = str(a) if a is not None else ''

And then add it to b:

b = 'WAKA' + a

Or, if you don't mind of converting zeros/Nones/empty-somethings to '', you can write something like it:

b = 'WAKA' + (a if a else '')

or:

b = 'WAKA' + (a or '')

I think these variants are nearly the fastest you can do in Python without C-code.

Upvotes: 2

Related Questions