English 中文(简体)
小型套数符合逻辑,或者在Schala。
原标题:Small set vs logical or in Scala
  • 时间:2023-09-08 05:21:10
  •  标签:
  • scala
  • set

I m seeing something like this in Scala code:

if (Set("foo", "bar").contains(x)) { ... }

一种明显的替代办法是,一种简单的OR条件:

if (x == "foo" || x == "bar") { ... }

除了可论证的更好的可读性外,使用原始方法的客观好处是什么? 是否有更多的表演者/消费较少的记忆?

注:

  1. In the real code, "foo" and "bar" are fixed instances of a case class
  2. There are just two elements in the condition. The likelihood of adding more elements in future is low.
最佳回答

我建议采用前一种做法的唯一原因是,如果这套方法具有某种可图性,或者如果它拥有如此庞大和完全的复杂数据,它实际上会有助益。

If that was the case, I would still give it a name and leverage the fact that contains is also aliased as apply for Sets to make it more readable (and avoid creating a lot of very short-lived data):

val isFooOrBar: String => Boolean = Set("foo", "bar")

if (isFooOrBar(x)) { ... }

关于业绩:

  1. there is a highly likelihood that this is not critical
  2. if it is critical, the only source of truth is measuring

在这方面,我确信,“很有可能取得更好的效果(没有数据可生成、低层抽象化、对时间很熟悉和JIT等),但即便如此,我还是将侧重于可读性。 如果<条码>类别相当庞大,你可能不想将整件内容放在<条码>中,但不妨碍你做以下工作:

def isFooOrBar(x: String): Boolean = x == "foo" || x == "bar"

if (isFooOrBar(x)) { ... }

which makes it indistinguishable at call-site what approach you took and is arguably readable anyway. Maybe the only improvement is to give the predicate a name that described more accurately the why, like in the following made-up snippet:

// anything but "foo" and "bar" are incompatible with the retroencabulator
def isCompatibleWithRetroencabulator(s: String) = ...

如果你上注意履约情况,就将其改为 私人,并可能将其附在@inline(及衡量标准);

问题回答

暂无回答




相关问题
In-place C++ set intersection

The standard way of intersecting two sets in C++ is to do the following: std::set<int> set_1; // With some elements std::set<int> set_2; // With some other elements std::set<int> ...

Creating a surface of triangles from a set of 2D points

I have a set of points and I need to convert the set to (non-overlapping) triangles (or a big polygon if equivalent)... The application: I have a list of locations (latitude,longitude) from a country,...

Check if a combination matches a given set

Basically I m looking for a solution which returns if a given combination matches a given set. Example: I have an array which stores which computer room and which workplace has which equipment. I ...

How can I concatenate set of results in MySQL?

I would like to join results returned in the set in MySQL with a comma as a separator string. For example, set returned contains: COLUMN_X john jerry maria joseph gugla I would like to receive the ...