Everything looks odd the first time you see it.
a, b := b, a
t := t
Both of those look odd to a programmer unfamiliar with either concept, the
can probably reason out the first one, the second is a little more
difficult, but the effort of learning why they work is well worth it.
As for lok order, if you don't want to put the defer first, then don't. If
a programmer cannot figure out that
defer mu.Unlock()
mu.Lock()
is functionally equivalent to
mu.Lock()
defer mu.Unlock()
then I don't think the main problem is the order. There is no need to add
extra comments (just like the first two examples given above). Also, if
you don't know why someone would use this order, and you stop and think
about it, hopefully you will come to the conclusion that it shortens the
critical section, also prompting you to think about your critical sections
and making sure they are short. Anyhow, use it or don't. My comment was I
do use it because defers are not free, which supported the OP's point. Ian
has said defers will become less expensive in the future. Great! I will
probably continue to use this order, I like what it implies, but you can
use what order you like. It is one of the great things about freewill ;-)
On Wed, Sep 2, 2015 at 1:03 AM, Will Newton wrote:On 2 September 2015 at 02:55, 'Paul Borman' via golang-nuts
wrote:
If Lock panics then the defer is the least of your concerns.
Fortunately, lock does not panic, it does not return an error. Lock does
what it says it does. I have no interest in coding around a hypothetical
Lock implementation that we don't use.
You are free to order those two statements how ever you want. For an
uncontested lock there is no difference in time. For a contested lock then
doing the defer first will shorten the critical section (not by much, but by
an amount you can measure). You are free to do them in either order, but
both are safe (unless your program has already lost memory safety, at which
point it does not matter) and functionally equivalent.
One measurable cost of these types of micro-optimization is that it
looks odd, so programmers who have not seen the idiom before may
change the statements back to the "right" order unless you add
comments explaining the idiom to every call site. In any case I would
expect truly performance critical critical sections to not use defer
at all.
My advice would be: do it in the natural order unless it measurably
improves performance to do otherwise, and then comment it.
--
Will Newton
Software - Cocoon (http://cocoon.life)
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit
https://groups.google.com/d/optout.