什么更有效?用一个元素初始化数组还是将一个元素推到一个空数组中?

huangapple go评论64阅读模式
英文:

What is more efficient? Initializing an array with an element or pushing an element to an empty array?

问题

以下是翻译好的部分:

关于效率是否有差异,还是一种偏好和代码可读性的问题?

例如,如果我有以下两个选项,哪个更有效率?

选项1:

let test = [1];

选项2:

let test = [];
test.push(1);

其中一个比另一个更好吗?

英文:

Is there any difference in terms of efficiency or is it a matter of preference and code readability?

For example if I have the two following options, which is more efficient?

Option 1:

let test = [1];

Option 2:

let test = [];
test.push(1);

Is one better than the other?

答案1

得分: 2

Initializing the array with a value takes approximately 7.5E⁻7 ms, while initializing an empty array and then using array.push takes around 1.925E⁻5. Initializing an array with a value is therefore significantly more performant than the second method. In addition, the first method uses only 1 line compared to the second method's 2 lines and is more readable.

英文:

Quickly testing in chrome's console:

const t = performance.now(), tests = 1e9;
for(let i=0;i<tests;i++){
    let test = [1];
}
(performance.now() - t) / tests;

and

const t = performance.now(), tests = 1e9;
for(let i=0;i<tests;i++){
    let test = [];
    test.push(1);
}
(performance.now() - t) / tests;

Initializing the array with a value takes approximately 7.5E⁻7 ms, while initializing an empty array and then using array.push takes around 1.925E⁻5. Initializing an array with a value is therefore significantly more performant than the second method.

In addition, the first method uses only 1 lines compared to the second method's 2 lines and is more readable.

huangapple
  • 本文由 发表于 2023年3月21日 01:53:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75793684-4.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定