相关疑难解决方法(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万
查看次数

如果声明有或没有否定

显然,这两个样本实现了同样的目的.但是,是否存在任何特定于实现的案例,其中一个可以比另一个具有更好的性能?

也许是一个愚蠢的问题,但这让我今天想到了.

编辑:该示例使用字符串,但这可以是任何东西,我的问题与字符串比较的速度等无关.

if (something == 'something') {
  return "something's up";
}
return;
Run Code Online (Sandbox Code Playgroud)

VS

if (something != 'something') {
  return;
}
return "something's up";
Run Code Online (Sandbox Code Playgroud)

language-agnostic if-statement

0
推荐指数
1
解决办法
125
查看次数