Skip to content

Instantly share code, notes, and snippets.

@carlos-jenkins
Created December 15, 2016 20:38
Show Gist options
  • Save carlos-jenkins/e3084a07402ccc25dfd0038c9fe284b5 to your computer and use it in GitHub Desktop.
Save carlos-jenkins/e3084a07402ccc25dfd0038c9fe284b5 to your computer and use it in GitHub Desktop.
Python3 string index lookup vs bytes index lookup
from random import choice
from datetime import datetime
from string import ascii_letters, digits
def generate_string(length, choices=ascii_letters + digits):
return ''.join(choice(choices) for _ in range(length))
def compare_lookup(length):
print('Allocating memory...')
mystring = generate_string(length)
mybytes = mystring.encode('utf-8')
print('Go!')
start = datetime.now()
for index in range(length):
at_index = mystring[index] # noqa
string_lookup = datetime.now() - start
start = datetime.now()
for index in range(length):
at_index = mybytes[index] # noqa
bytes_lookup = datetime.now() - start
print('String lookup: {} ms'.format(
string_lookup.total_seconds())
)
print('Bytes lookup : {} ms'.format(
bytes_lookup.total_seconds())
)
compare_lookup(10000000)
@carlos-jenkins
Copy link
Author

$ python3 lookups.py
Allocating memory...
Go!
String lookup: 0.513942 ms
Bytes lookup : 0.486462 ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment