I want to optimize.
Simple solution
connection = get_db_connection()
for item in my_iterator:
push_item_to_db(item, connection)
Drawback:
get_db_connection() is slow. If my_iterator is empty, then I want to avoid to call it.
"if None" solution
connection = None
for item in my_iterator:
if connection is None:
connection = get_db_connection()
push_item_to_db(item, connection)
Drawback:
If there are 100k items in my_iterator, then if connection is None gets called 100k times (although it is needed only once). I want to avoid this.
Perfect solution ...
- don't call
get_db_connection()if iterator is empty - don't call
if connection is None:uselessly for every iteration.
Any idea?
if not iis an insignificant overhead compared to whatever will happen inpush_item_to_db.get_db_connectionis slow, "optimizing" to avoid anifstatement doesn't seem the right thing to do... That said, your iterator ought to throw aStopIterationthat terminates the for each loop when it is empty.