英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论