質問

達成できますか

if (a == "b" || "c")

の代わりに

if (a == "b" || a== "c")

役に立ちましたか?

解決

いいえ、次のことができます:

if (new[] { "b", "c" }.Contains(a))

LINQ 拡張機能を使用できる場合、それはほとんど改善されません。

>

パフォーマンスに関するコメントに応えて、基本的なタイミングコードをいくつか示します。コードは批判的な目で見なければならないことに注意してください。タイミングを歪めることをここでやったかもしれません。

最初に結果:

||, not found: 26 ms
||, found: 8 ms
array.Contains, not found: 1407 ms
array.Contains, found: 1388 ms
array.Contains, inline array, not found: 1456 ms
array.Contains, inline array, found: 1427 ms
switch-statement, not interned, not found: 26 ms
switch-statement, not interned, found: 14 ms
switch-statement, interned, not found: 25 ms
switch-statement, interned, found: 8 ms

すべてのコードが2回実行され、nrのみが渡されます。式からJITtingのオーバーヘッドを除去するために2が報告されました。両方のパスが各タイプのチェックを100万回実行し、検索する要素がそれを見つける要素の1つであった場合(つまり、ifステートメントがブロックを実行する場合)、および要素がなかった場合に1回実行しました(ブロックは実行されません)。それぞれのタイミングが報告されます。事前に構築された配列と毎回構築される配列の両方をテストしましたが、この部分はコンパイラがどれだけ推測して最適化するかわかりません。ここに欠陥があるかもしれません。

いずれにせよ、最初に文字列を挿入するかどうかにかかわらず、switch-statementを使用すると、単純なor-statementとほぼ同じ結果が得られるように見えますが、array-lookupははるかに費用がかかりますが、これも私には予想されていました。

コードをいじって、問題がある場合は修正(またはコメント)してください。

そして、ここにかなり長いソースコードがあります:

using System;
using System.Linq;
using System.Diagnostics;
namespace StackOverflow826081
{
    class Program
    {
        private const Int32 ITERATIONS = 1000000;
        static void Main()
        {
            String a;
            String[] ops = CreateArray();
            Int32 count;
            Stopwatch sw = new Stopwatch();
            Int32 pass = 0;
            Action<String, Int32> report = delegate(String title, Int32 i)
            {
                if (pass == 2)
                    Console.Out.WriteLine(title + ": " + sw.ElapsedMilliseconds + " ms");
            };

            for (pass = 1; pass <= 2; pass++)
            {
                #region || operator

                a = "a";
                sw.Start();

                count = 0;
                for (Int32 index = 0; index < ITERATIONS; index++)
                {
                    if (a == "b" || a == "c")
                    {
                        count++;
                    }
                }
                sw.Stop();
                report("||, not found", count);
                sw.Reset();

                a = "b";
                sw.Start();

                count = 0;
                for (Int32 index = 0; index < ITERATIONS; index++)
                {
                    if (a == "b" || a == "c")
                    {
                        count++;
                    }
                }
                sw.Stop();
                report("||, found", count);
                sw.Reset();

                #endregion

                #region array.Contains

                a = "a";
                sw.Start();

                count = 0;
                for (Int32 index = 0; index < ITERATIONS; index++)
                {
                    if (ops.Contains(a))
                    {
                        count++;
                    }
                }
                sw.Stop();
                report("array.Contains, not found", count);
                sw.Reset();

                a = "b";
                sw.Start();

                count = 0;
                for (Int32 index = 0; index < ITERATIONS; index++)
                {
                    if (ops.Contains(a))
                    {
                        count++;
                    }
                }
                sw.Stop();
                report("array.Contains, found", count);
                sw.Reset();

                #endregion           

                #region array.Contains

                a = "a";
                sw.Start();

                count = 0;
                for (Int32 index = 0; index < ITERATIONS; index++)
                {
                    if (CreateArray().Contains(a))
                    {
                        count++;
                    }
                }
                sw.Stop();
                report("array.Contains, inline array, not found", count);
                sw.Reset();

                a = "b";
                sw.Start();

                count = 0;
                for (Int32 index = 0; index < ITERATIONS; index++)
                {
                    if (CreateArray().Contains(a))
                    {
                        count++;
                    }
                }
                sw.Stop();
                report("array.Contains, inline array, found", count);
                sw.Reset();

                #endregion

                #region switch-statement

                a = GetString().Substring(0, 1); // avoid interned string
                sw.Start();

                count = 0;
                for (Int32 index = 0; index < ITERATIONS; index++)
                {
                    switch (a)
                    {
                        case "b":
                        case "c":
                            count++;
                            break;
                    }
                }
                sw.Stop();
                report("switch-statement, not interned, not found", count);
                sw.Reset();

                a = GetString().Substring(1, 1); // avoid interned string
                sw.Start();

                count = 0;
                for (Int32 index = 0; index < ITERATIONS; index++)
                {
                    switch (a)
                    {
                        case "b":
                        case "c":
                            count++;
                            break;
                    }
                }
                sw.Stop();
                report("switch-statement, not interned, found", count);
                sw.Reset();

                #endregion                      

                #region switch-statement

                a = "a";
                sw.Start();

                count = 0;
                for (Int32 index = 0; index < ITERATIONS; index++)
                {
                    switch (a)
                    {
                        case "b":
                        case "c":
                            count++;
                            break;
                    }
                }
                sw.Stop();
                report("switch-statement, interned, not found", count);
                sw.Reset();

                a = "b";
                sw.Start();

                count = 0;
                for (Int32 index = 0; index < ITERATIONS; index++)
                {
                    switch (a)
                    {
                        case "b":
                        case "c":
                            count++;
                            break;
                    }
                }
                sw.Stop();
                report("switch-statement, interned, found", count);
                sw.Reset();

                #endregion
            }
        }

        private static String GetString()
        {
            return "ab";
        }

        private static String[] CreateArray()
        {
            return new String[] { "b", "c" };
        }
    }
}

他のヒント

まあ、あなたが得ることができる最も近いものは:

switch (a) {
   case "b":
   case "c":
      // variable a is either "b" or "c"
      break;
}

私の知る限り、これはオプションではありません。

正規表現を使用できます:

if(Regex.IsMatch(a, "b|c"))

「a」の内容がこれは1文字より長くすることができます:

if(Regex.IsMatch(a, "^(b|c)<*>quot;))

いいえ、その構文ではありません。しかし、それをコーディングする多くのオプションがあります。

if ("bc".Contains(a)) { } // Maybe check a.Length == 1, too.

if ((a[0] & 0x62) == 0x62) { } // Maybe check a.Length == 1, too.

if (new String[] { "b", "c" }.Contains(a)) { }

演算子のオーバーロードを実行して構文を機能させることもできますが、これは実際に何を達成したいかによって異なり、簡単な例ではわかりにくいです。

特定の状況では可能です。つまり、フラグ付き列挙:

[Flags]
enum MyEnum {
    None = 0,
    A = 1,
    B = 2,
    C = 4,
    D = 8
}

//...

MyEnum a = MyEnum.B

if((a & (MyEnum.B | MyEnum.C)) > 0)
    // do something

は次と同等です:

if((a & MyEnum.B) > 0 || (a & MyEnum.C) > 0)
    // do something

この理由は、ビットマスクに関係しています。バイナリでは、

None = 00000
A    = 00001
B    = 00010
C    = 00100
D    = 01000

したがって、|を使用するとき演算子の場合、列の1を探してビットごとに比較し、結果にコピーします。列に1がない場合は、0をコピーします。

  B 00010
& C 00100
---------
    00110

その後、&amp;演算子、1をコピーする前に、各列のすべての行で1を探します。

  (B & C) 00110
& (a = B) 00010
---------------
          00010

は次のとおりです&gt; 0、したがってtrueを返します。

奇妙なことに、これは最も効率的な方法です。数値比較(&gt;)と論理演算子(||)を節約できるためです。

いいえ、これはC#でのor演算子(||)の動作ではありません。

別の解決策は、コードを読みにくくしますが、必要な値をチェックする関数を作成することです。次のようなものです。

public static bool Any(object a, params object[] b)
{
    foreach(object item in b)
    {
        if(a == b)
        {
            return true;
        }
    }
    return false;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top