Created
December 15, 2016 20:38
-
-
Save carlos-jenkins/e3084a07402ccc25dfd0038c9fe284b5 to your computer and use it in GitHub Desktop.
Python3 string index lookup vs bytes index lookup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Author
carlos-jenkins
commented
Dec 15, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment