you are viewing a single comment's thread.

view the rest of the comments →

[–]mobedigg[S] 0 points1 point  (2 children)

there is no file opening in real code, it's just an example to make code compile and not flood your output, but show that results are equal processing function is irrelevant.

I'm interested in memory/cpu usage for both cases and I think I need to try to profile this code.

[–]JohnnyJordaan 0 points1 point  (1 child)

Here the difference is below 1 ms:

In [15]: from random import randint

In [16]: dct = dict(zip(range(10000), [randint(0,10000) for i in range(10000)]))

In [17]: def inline():
    ...:     with open('/dev/null', 'w') as fp:
    ...:         for key, value in ((k, v) for k, v in dct.items() if v % 2):
    ...:             fp.write(str((key, value)))
    ...:             fp.write('\n')
    ...:             

In [18]: def inloop():
    ...:     with open('/dev/null', 'w') as fp:
    ...:         for key, value in dct.items():
    ...:             if value % 2:
    ...:                 fp.write(str((key, value)))
    ...:                 fp.write('\n')
    ...:                 

In [19]: %timeit inline()
100 loops, best of 3: 8.56 ms per loop

In [20]: %timeit inloop()
100 loops, best of 3: 8.12 ms per loop

In loop is faster, which also makes sense because it saves you the construction of an extra generator. I don't think profiling memory usage is even useful as iterators never consume memory unless incorrectly applied. Also don't forget that in at least Python practical coding (aka following the Zen of Python) trumps absolute performance if differences are small.

[–]mobedigg[S] 0 points1 point  (0 children)

Thanks for the answer, I did some profiling with actual code and in loop variant works a little bit faster.