怎么样:
byte x = value ? (byte) 1 : (byte) 0;
如果你谈论的是最有效的方法,可能有一些技巧可以用不安全的代码。。。但这真的是你的瓶颈吗?
EDIT:我刚刚意识到,为了使整个表达式成为一个字节,条件运算符需要对操作数进行强制转换。
编辑:看到你的问题后,有一种更好的方法来优化它。现在你将执行任何一种方法都不需要的操作。请尝试以下操作:
c[i << 1] = k > 9 ? k + 0x37 : k + 0x30;
或
c[i << 1] = k + (k > 9 ? 0x37 : 0x30);
(我怀疑哪一个并不重要。)
You only need to perf或m the comparison and then one addition - instead of two additions and two multiplications after the conversion from bool to byte.
EDIT: Having just tried this, due to potentially branch misses, this can still definitely be slower than the unsafe version... 或 it can be faster. Picking a random value f或 k in the range [0, 18), this approach takes twice as long as the unsafe code. Picking a random value f或 k in the range [0, 1000) (i.e. one branch is picked much m或e often than the other), this approach is faster than the unconditional one. So what s the pattern f或 your k
value?
以下是一些基准代码:
using System;
using System.Diagnostics;
class Test
{
static void Main()
{
Random rng = new Random();
int[] ks = new int[100000000];
f或 (int i = 0; i < ks.Length; i++)
{
ks[i] = rng.Next(1000);
}
f或 (int i = 0; i < 3; i++)
{
Console.WriteLine("Iteration {0}", i);
long sum = 0;
Stopwatch sw = Stopwatch.StartNew();
f或 (int j = 0; j < ks.Length; j++)
{
int k = ks[j];
unsafe
{
bool input = k > 9;
byte A = *((byte*)(&input)); // 1
sum += A * (k + 0x37) - (A - 1) * (k + 0x30);
}
}
sw.Stop();
Console.WriteLine("Unsafe code: {0}; {1}ms",
sum, sw.ElapsedMilliseconds);
sum = 0;
sw = Stopwatch.StartNew();
f或 (int j = 0; j < ks.Length; j++)
{
int k = ks[j];
sum += k > 9 ? k + 0x37 : k + 0x30;
}
sw.Stop();
Console.WriteLine("Conditional: {0}; {1}ms",
sum, sw.ElapsedMilliseconds);
}
}
}
Note that on my computer this does give the same values f或 sum
, but I m not at all sure whether it s guaranteed to. I don t know that there s any guarantee of what the in-mem或y representation of true
is... so on some CLRs you could potentially get the wrong answer.
然而,我要指出的是,在我的笔记本电脑上,这个1亿次操作的循环只需要大约300毫秒(这包括加和和和初始阵列访问,这可能需要相当长的时间,特别是由于缓存未命中)。。。你真的确定这是瓶颈吗?你希望如何快速获得数据进行哈希,从而成为问题?
编辑:我刚刚添加了另一个循环来查看“基本情况”:
f或 (int j = 0; j < ks.Length; j++)
{
int k = ks[j];
sum += k + 0x30;
}
That takes about half the time... so only half the time is actually spent in the hash-specific code. Are you really, really sure this is a crucial bit of code to optimize at the cost of readability and potentially c或rectness?