相关疑难解决方法(0)

为什么处理排序数组比处理未排序数组更快?

这是一段看似非常特殊的C++代码.出于某种奇怪的原因,奇迹般地对数据进行排序使得代码几乎快了六倍.

#include <algorithm>
#include <ctime>
#include <iostream>

int main()
{
    // Generate data
    const unsigned arraySize = 32768;
    int data[arraySize];

    for (unsigned c = 0; c < arraySize; ++c)
        data[c] = std::rand() % 256;

    // !!! With this, the next loop runs faster.
    std::sort(data, data + arraySize);

    // Test
    clock_t start = clock();
    long long sum = 0;

    for (unsigned i = 0; i < 100000; ++i)
    {
        // Primary loop
        for (unsigned c = 0; c < arraySize; ++c) …
Run Code Online (Sandbox Code Playgroud)

c++ java optimization performance branch-prediction

2万
推荐指数
27
解决办法
142万
查看次数

Java中"x == 7"到1(真)或0(假)的快速恒定时间评估

我想将一个加密函数从C移植到Java.该函数必须在恒定时间内运行,因此不允许使用条件分支(并且不允许基于x的表查找).

原始的C代码是:

int x,result;
...
result = (x==7);
...
Run Code Online (Sandbox Code Playgroud)

因此,如果'x == 7','result'设置为1,否则设置为0.然后将'result'变量用于进一步的计算.

我现在正在寻找将其转换为Java的最佳方法.就像在Java表达式中评估为布尔值而不是整数一样,必须使用运算符来模拟上述情况.

我目前正在使用

int x,result;
...
result = (1<<(x-7))&1;
...
Run Code Online (Sandbox Code Playgroud)

这对我来说很好,因为我的x在{0,...,15}范围内.(请注意,shift函数仅使用低5位,因此当x太大时,您将得到误报.)

表达式将被评估数百万次,因此如果有一个聪明的解决方案只使用2个运算符而不是3个运算符,这将使整体计算更快.

java performance bit-manipulation constant-time

7
推荐指数
3
解决办法
1294
查看次数

Is there any cleaner way to write multiple if-statements in Java

I have an if-else structure in Java as follow:

                    if (A || B || C){
                        if (A){
                            //Do something
                        }
                        if (B){
                            //Do something
                        }
                        if (C){
                            //Do something
                        }
                    } else {
                        //Do something
                    }
Run Code Online (Sandbox Code Playgroud)

I want to know if there is any cleaner and easier way to replace this?

java if-statement

2
推荐指数
1
解决办法
144
查看次数