Python Performance / Place Holder vs Format

Place holder vs Format

By Marcelo Fernandes Jul 11, 2017

Proposal:

Given that I am comparing two ways of manipulate strings in python, detect which one is the fastest one.

Place Holder Syntax

"Place Holder" is a string formatting syntax that python borrowed from C.
Its use is pretty straight forward, follow the example:

# Via Place Holder.
greetings = "Hello %s" % "world"
print(greetings)
# "Hello World"

.format Syntax

Although there are more sophisticated uses for .format(), we are mainly concerned about simple uses case.

greetings = "Hello {}".format('World')
print(greetings)
# 'Hello World'

Comparative in timeit module

Runs a Million times each validation

from timeit import timeit

place_holder_time = timeit(stmt="""'Hello %s' % 'World'""", number=1000000)
format_time = timeit(stmt="""'Hello {}'.format('World')""", number=1000000)

print(place_holder_time)
# 0.014078450010856614
print(format_time)
# 0.2000601239997195


Comparative via dis: Disassembler for Python bytecode.


from dis import dis


def place_hold_function(string):
    return 'Hello %s' % string

dis(place_hold_function)
#  0 LOAD_CONST               1 ('Hello %s')
#  3 LOAD_FAST                0 (string)
#  6 BINARY_MODULO
#  7 RETURN_VALUE

def format_function(string):
    return 'Hello {}'.format(string)

dis(format_function)
# 0 LOAD_CONST               1 ('Hello {}')
# 3 LOAD_ATTR                0 (format)
# 6 LOAD_FAST                0 (string)
# 9 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
# 12 RETURN_VALUE


Notes


String formatting also supports other data types as %f for floats.