[Tutor] Regular User defined functions Vs Generator functions

Mats Wichmann mats at wichmann.us
Sat Oct 31 13:54:04 EDT 2020


On 10/31/20 2:50 AM, Alan Gauld via Tutor wrote:
> On 31/10/2020 01:38, Manprit Singh wrote:
> 
>> I have a question , why not to prefer generator functions instead of
>> regular user defined functions, where i have problem like as that given
>> below :
> 
> Any function that returns a potentially long sequence of values
> is probably better written as a generator. It's just that from habit
> most folks use return.  It's easy enough to convert a regular
> function to a generator if it turns out that performance needs
> it. But there's absolutely nothing wrong with doing it from
> the beginning.
> 
> There may be a slight performance overhead in using a generator
> where there are very low numbers of return values, but it's
> minimal and as in any performance assessment you'd need to
> measure it to determine whether the list or generator
> approach worked best.

It may be a false economy to even worry about it, but my tendency is if
the caller is going to immediately consume the entire result of the
function, and there's potentially a large number of values, then there's
not really any point in having it be a generator, you don't realize any
of the savings and you pay the cost of function setup/call for each
value.  That's really kind of stupid on the surface, you shouldn't
decide on the implementation of a function based on usage pattern of one
frequent caller, since that's breaking the separation of purpose that
the function should give you, but the thing I'm spending most of my time
on does have some performance issues, so....




More information about the Tutor mailing list