这是一段看似非常特殊的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) 我在 nodejs/chrome/v8 中发现了一个奇怪的行为。似乎这段代码:
var x = str.charCodeAt(5);
x = str.charCodeAt(5);
Run Code Online (Sandbox Code Playgroud)
比这更快
var x = str.charCodeAt(5); // x is not greater than 170
if (x > 170) {
x = str.charCodeAt(5);
}
Run Code Online (Sandbox Code Playgroud)
起初我虽然可能比较比实际的第二次调用更昂贵,但是当 if 块中的内容没有调用时str.charCodeAt(5)
,性能与单次调用相同。
为什么是这样?我最好的猜测是 v8 正在优化/取消优化某些东西,但我不知道如何准确地解决这个问题或如何防止这种情况发生。
这是 jsperf 的链接,它至少在我的机器上很好地展示了这种行为:https ://jsperf.com/charcodeat-single-vs-ifstatment/1
背景:我发现这个的原因是因为我试图优化babel-parser内部的令牌读取。
我测试过,str.charCodeAt()
速度是str.codePointAt()
我的两倍,但我可以替换此代码:
var x = str.codePointAt(index);
Run Code Online (Sandbox Code Playgroud)
和
var x = str.codePointAt(index);
Run Code Online (Sandbox Code Playgroud)
但是由于上述行为,第二个代码没有给我任何性能优势。