Better to use “and” or “in” when chaining “let” statements?

前端 未结 4 1404
耶瑟儿~
耶瑟儿~ 2021-02-19 09:57

I realize this is probably a silly question, but...

If I\'m chaining a bunch of let statements which do not need to know each other\'s values, is it

4条回答
  •  眼角桃花
    2021-02-19 10:18

    The answer to the question "which is better?" only really makes sense when the interpretations do not differ. The ML family of languages (at least SML and OCaml) have both a parallel initialization form (and) and a sequential, essentially nested-scope form (in) because they are both useful in certain situations.

    In your case the semantics are the same, so you are left to answer the question "what reads best to you?" and maybe (if this is not premature) "which might be executed more efficiently?" In your case the alternatives are:

    • For the and case: evaluate a bunch of strings and do a parallel binding to three identifiers.

    • For the in case: bind foo to a, then bind bar to b, then bind baz to c.

    Which reads better? It is a toss up in this case because the outcome does not matter. You can poll some English speakers but I doubt there will be much preference. Perhaps a majority will like and as it separates bindings leaving the sole in before the expression.

    As to what executes more efficiently, I think a good compiler will likely produce the same code because it can detect the order of binding will not matter. But perhaps you have a compiler that generates code for a multicore processor that does better with and. Or maybe a naive compiler which writes all the RHSs into temporary storage and then binds them, making the and case slower.

    These are likely to be non-essential optimization concerns, especially since they involve bindings and are probably not in tight loops.

    Bottom line: it's a true toss-up in this case; just make sure to use parallel vs. sequencial correctly when the outcome does matter.

提交回复
热议问题