dharmik on Nostr: so i did a few tests to compare a for loop and a generator in python for performance. ...
so i did a few tests to compare a for loop and a generator in python for performance.
1. first test: sum of squares up to n (n = 106)**
results:
using for-loop:
time taken: 0.271047 seconds
memory used (result): 32 bytes
using generator:
time taken: 0.278367 seconds
memory used (result): n/a
the generator was slightly slower than the for-loop, which was surprising, since i expected the generator to be faster.
2. increased complexity test:
next, i made the test more complex by adding conditional logic (square even numbers, double odd ones) and using dictionaries instead of lists. the results were something like:
Using for-loop:
Time taken: 0.998669 seconds
Memory used (result): 32 bytes
Using generator:
Time taken: 0.990227 seconds
Memory used (result): N/A
yes, now the generator was faster, though slightly. it appears the change is only there when the dataset is bigger.
1. first test: sum of squares up to n (n = 106)**
results:
using for-loop:
time taken: 0.271047 seconds
memory used (result): 32 bytes
using generator:
time taken: 0.278367 seconds
memory used (result): n/a
the generator was slightly slower than the for-loop, which was surprising, since i expected the generator to be faster.
2. increased complexity test:
next, i made the test more complex by adding conditional logic (square even numbers, double odd ones) and using dictionaries instead of lists. the results were something like:
Using for-loop:
Time taken: 0.998669 seconds
Memory used (result): 32 bytes
Using generator:
Time taken: 0.990227 seconds
Memory used (result): N/A
yes, now the generator was faster, though slightly. it appears the change is only there when the dataset is bigger.