问题
看到了一个倒置数组的算法,然后做了简单的基准测试,发现浏览器内置的 reverse
方法比自己写的算法快很多
代码
let test = [...Array(1000).keys()];
// 常规方法,倒着 for 循环
function test1(params) {
let arr = [];
for(let i = test.length - 1; i >= 0; i--) {
arr.push(test[i]);
}
return arr;
}
// 交换法
function test2(params) {
let arr = [...test];
for(let i = 0; i < arr.length / 2; i++) {
let temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
return arr;
}
// Js 的 reverse 方法
function test3(params) {
return test.reverse();
}
console.time('test1');
test1(test);
console.timeEnd('test1');
console.time('test2');
test2(test);
console.timeEnd('test2');
console.time('test3');
test3(test);
console.timeEnd('test3');
后记
我翻了一下 v8 的代码,但是没找到,搜索结果太多了,找到一个参考的代码 src/builtins/array-reverse.tq
,src/builtins/builtins-typed-array.cc
还有一些倒置相关的方法函数,这都是 v8 里面的
static void FillDigits32(uint32_t number, Vector<char> buffer, int* length) {
int number_length = 0;
// We fill the digits in reverse order and exchange them afterwards.
while (number != 0) {
int digit = number % 10;
number /= 10;
buffer[(*length) + number_length] = '0' + digit;
number_length++;
}
// Exchange the digits.
int i = *length;
int j = *length + number_length - 1;
while (i < j) {
char tmp = buffer[i];
buffer[i] = buffer[j];
buffer[j] = tmp;
i++;
j--;
}
*length += number_length;
}
参考文章
- https://afteracademy.com/blog/reverse-an-array
- https://www.geeksforgeeks.org/write-a-program-to-reverse-an-array-or-string/
- https://zhuanlan.zhihu.com/p/55338902
- https://stackoverflow.com/questions/13446654/why-is-a-custom-array-reverse-implementation-twice-as-fast-versus-reverse-in
- https://stackoverflow.com/questions/7912677/javascripts-array-reverse/7912713#7912713
- https://stackoverflow.com/questions/5276953/what-is-the-most-efficient-way-to-reverse-an-array-in-javascript