Python and the need for speed

Nathan Ernst nathan.ernst at gmail.com
Tue Apr 11 20:44:33 EDT 2017


goto is a misunderstood and much misaligned creature. It is a very useful
feature, but like nearly any programming construct can be abused.

Constructs like 'break', 'continue' or 'next' in languages like Python or
C/C++ are goto's with implied labels.

As Mikhail said, goto's can be great to break out of nested loops (only a
handful of languages support named 'breaks').

So, instead of:
bool found = false;
for (int i = 0; i = ...; ++i)
{
 for (int h = 0; h = ...; ++h)
 {
   if (some_condition)
     found = true;
 }
 if (found) break;
}

You can have:

for (int i = 0; i = ...; ++i)
{
 for (int h = 0; h = ...; ++h)
 {
   if (some_condition)
     goto found;
 }
}
// not found

found:
// handle found

The second is better for a number of reasons: it's clearer. It has fewer
variables (smaller stack), it has fewer branches (better for the CPU's
branch prediction), and it has fewer instructions (better for CPU
instruction cache).  This is a trivial, contrived example, but I've seen
more than 4x nested loops using an exit flag like this (at every level of
the loops) that could have been replaced with a lot less code.

People need to stop drinking "X is considered harmful." Even Dijkstra later
lamented that his "Goto considered harmful" paper was misinterpreted and
misrepresented as advocating that goto should never be used.

Additionally, I'd recommend everyone read '"Considered Harmful" Essays
Considered Harmful': http://meyerweb.com/eric/comment/chech.html

Regards,
Nate

On Tue, Apr 11, 2017 at 6:04 PM, Mikhail V <mikhailwas at gmail.com> wrote:

> On 12 April 2017 at 00:02, Rick Johnson <rantingrickjohnson at gmail.com>
> wrote:
> > On Monday, April 10, 2017 at 7:25:48 AM UTC-5, Mikhail V wrote:
> >> Still I miss some old school features in Python, e.g.
> >> "goto" statement would be very useful in some cases.
> >
> > Are you serious?
>
> Not so serious to think it is needed much.
> And it easy enough to imagine where it
> would be more readable than setting up flags and if-blocks
> just to jump along the script.
>
> n.d., it reminds me also about the discussion about
> exiting from nested loops.
> --
> https://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list