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

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

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

问题

Option 1:

let test = [1];

Option 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-2.html
匿名

发表评论

匿名网友

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

确定