Created
January 10, 2012 17:17
-
-
Save dlitvakb/1590081 to your computer and use it in GitHub Desktop.
map vs list comprehension
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
| import timeit | |
| def strip(a_string): | |
| return a_string.strip() | |
| results_map = [] | |
| results_list_comprehension = [] | |
| comp_list = [' 123', ' 123', '123', '123 ','123 '] | |
| def strip_map(): | |
| map(strip, comp_list) | |
| def strip_comp(): | |
| [strip(x) for x in comp_list] | |
| for x in range(100): | |
| results_map.append(timeit.Timer(setup='from __main__ import strip_map', stmt='strip_map()')) | |
| for x in range(100): | |
| results_list_comprehension.append(timeit.Timer(setup='from __main__ import strip_comp', stmt='strip_comp()')) | |
| result_map = 0.0 | |
| for timer in results_map: | |
| result_map += timer.timeit() | |
| result_list_comprehension = 0.0 | |
| for timer in results_list_comprehension: | |
| result_list_comprehension += timer.timeit() | |
| print result_map / float(len(results_map)) | |
| print result_list_comprehension / float(len(results_list_comprehension)) | |
| ########### | |
| # Results # | |
| ########### | |
| # Map | |
| 1.502139256 | |
| # List Comprehension | |
| 1.63835688829 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment