Python and the need for speed

Rick Johnson rantingrickjohnson at gmail.com
Wed Apr 12 00:41:28 EDT 2017


On Tuesday, April 11, 2017 at 7:44:49 PM UTC-5, Nathan Ernst wrote:
> 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
>

I'll admit, that in a few cases of deeply nested loops, i
have purposely stripped out the nested code and wrapped it
in a function so i could take advantage of return, because
indeed, flags are distracting. However, i don't think this
one example is enough to warrent a goto. Unless you can
provide more than one legitimate use for goto, i'd rather
support a new keyword like "breakall". In fact, the more i
think about it, the more i realize that it should have been
"breaklocal" and "breakglobal" all along! Hmm, how would goto
handle a logic that required both a local and a global
break within the same nested loop structure?

> 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.

But it also requires a named target. (Although i'll admit,
goto does offer more _flexibility_ over a single
"breakglobal" keyword)




More information about the Python-list mailing list