更快的方法是:创建一个新的数组或遍历现有数组? [英] What is the faster: to create a new array or iterate through existing?

查看:58
本文介绍了更快的方法是:创建一个新的数组或遍历现有数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,例如(在Java中)

I have an array, for example (in Java)

int[] a = new int[N];

我已经使用过它,现在想要具有零的数组.将会花费更少的时间:创建一个新的Array(它将初始化为零)或遍历现有的Array并用零填充它?

I have worked with it and now want to have array with zeros. What will take less time: to create a new Array(it will be initialized will zeros) or iterate through existing one and fill it with zeros?

我想无论答案是什么,在C ++中都一样吗?

I suppose whatever answer is, it will be the same in C++ ?

推荐答案

相比于创建一个新数组,您最好填充一个现有数组.相对而言,内存分配可能非常昂贵.的确,如果您喜欢的语言为您提供了可以确保被清零的新数组,那么它很可能会在幕后为您填充.

Chances are that you're better off filling an existing array than creating a new one. Memory allocation can be very expensive relatively speaking. Indeed, if your favorite language provides you new arrays that are guaranteed to be zeroed out, it is probably filling them for you under the covers.

也就是说,这种选择是微优化.在大多数情况下,它不会有任何明显的不同.而且,如果您发现自己在特定情况下可能会产生重要的变化,那么问问探查器要好于问问StackOverflow.

That said, this type of choice is a micro-optimization. In most cases, it won't make any discernible difference. And if you find yourself in a specific case where you think it might make an important difference, you're much better asking a profiler than asking StackOverflow.

编辑:我还要补充一点警告:特别是在Java之类的垃圾收集语言中,如果可以干净地进行重用,那么最好不要重用现有对象,而要创建新对象.根据一般经验法则.

Edit I'll add one more caveat: Particularly in garbage collected languages like Java, you're better off reusing existing objects than creating new ones if the reuse can be done cleanly. As a general rule of thumb.

重新编辑 ...除非所讨论的对象预期寿命很短.可能还会有一些其他警告.然后回到询问探查器".

Reedit ... Unless the object(s) in question are expected to be very short lived. Probably some additional caveats too. And so back to "ask the profiler."

这篇关于更快的方法是:创建一个新的数组或遍历现有数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆