C#,在for..loop中声明变量,会降低性能吗?
例如:
for (i = 0; i < 100; i++)
{
string myvar = "";
// Some logic
}
它是否会导致性能或内存泄漏?
为什么我这样做,因为我不希望在 for..loop 之外访问“myvar”。
它是任何性能监视器,我可以比较两个片段或整个程序之间的执行时间?
感谢您。
For example:
for (i = 0; i < 100; i++)
{
string myvar = "";
// Some logic
}
Do it make performace or memory leak?
Why i do this, because i don't want "myvar" accessible outside the for..loop.
It is any performance monitor, i can compare the execute time between two snippet or whole program ?
thanks you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
不,变量纯粹是为了程序员的方便。在哪里声明它们并不重要。请参阅我的回答这个重复的问题了解更多详细信息。
No, variables are purely for the programmer's convenience. It doesn't matter where you declare them. See my answer to this duplicate question for more details.
也许你可以看看我曾经做过的关于另一次谈话的旧测试。 变量声明。优化方式
结果证明,重新定义速度更快,但内存不那么容易。
我的简单测试。我初始化了一个对象 100,000,000 次,创建一个新对象显然比重新使用旧对象更快:O
Perhaps you could check out an old test that I once did regarding another conversation. Variable declaration. Optimized way
The results turned out that it was faster to redefine but not as easy on memory.
My simple test. I initialised an object 100,000,000 times and it is was apparently faster to create a new one instead of re-using an old one :O
我相信这将是一个性能问题。由于虚拟机需要分配内存来存储每个循环对字符串的引用。即使引用可能是同一个 String 实例,但每次循环时都分配内存并不是更好的选择。
I believe this would be a performance problem. Since the VM would need to allocate memory to store a reference to the String every loop. Even though the reference may be to the same String instance, allocating memory every time it goes around the loop would not be preferable.
更新:
如果您使用与循环相同类型的变量,您可以执行我最初建议的操作:
否则不用担心,因为其他人已经建议了
@phoog,谢谢检查答案
UPDATE:
if your are using the same type of variable as the loop you could do what I originally sugested:
otherwise don't worry about it as others already suggested
@phoog, thx for checking the answer
提供一个现实生活中的例子:
我刚刚写完一个 .obj 模型加载器,当然它包含一些嵌套循环。
我在循环上方声明了所有变量,但后来我开始想知道与OP相同的事情并找到了这个线程。因此,我尝试将所有变量声明移至循环中使用它们的第一个点,实际上看到了很小的性能提升。以前平均加载时间为 380 毫秒(实际上为 370-400 毫秒)的模型现在加载速度始终快了约 15-20 毫秒。虽然只有 5% 左右,但仍然是一个进步。
我的循环构造仅包含一个 foreach 循环和一个嵌套的 for 循环,但还包含许多 if 语句。我移动了 5 个变量声明,其中大部分是字符串和整数数组。
To provide a real life example:
I just finished writing a .obj model loader which, of course, contains some nested loops.
I declared all my variabeles above my loops but then I started wondering the same thing as the OP and found this thread. So I tried and moved all variable declarations to the first point in my loop where I use them and actually saw a small performance gain. A model that previously took 380 ms on average to load (370-400 ms actually) now consistently loads about 15-20 ms faster. This is just about 5% but nontheless an improvement.
My loop construct consists of just a foreach-loop and a nested for-loop but also contains a lot of if-statements. I moved 5 variable declarations, most of which are arrays of strings and ints.
是的,这会产生内存使用问题。我不认为这会导致内存泄漏,因为垃圾收集器最终会收集未使用的对象,但这会对应用程序的性能产生负面影响。
我建议您使用在 for 循环范围之外声明的字符串生成器。
Yes, that would create a memory usage problem. I don't believe it would result in a memory leak as the Garbage Collector would eventually collect the unused objects, but that will have a negative impact on the performance of the application.
I would recommend you use a string builder declared outside the scope of the for loop.
它不会完全降低性能或导致内存泄漏,但仍然需要小心。
字符串是不可变的,这意味着一旦创建,就无法更改。通过在循环内创建新字符串,您将创建至少 n 个字符串变量。如果您尝试在循环内进行字符串操作,则应考虑使用
StringBuilder
。It won't exactly decrease performance or cause a memory leak, but it is still something to be cautious of.
Strings are immutable, which means that once created, they can't be changed. By creating a new string inside the loop, you are creating at least n string variables. If you're trying to do string manipulation inside a loop, you should consider using a
StringBuilder
instead.除非编译器以某种方式优化您的代码,否则在 for 循环内声明变量将需要分配新变量并收集旧变量。话虽这么说,编译器在优化代码方面做得非常好。
如果您想要一种快速方法来测试两个场景,请使用 StopWatch 类来测量执行每个案例所需的时间。我的猜测是,这种差异将不存在甚至可以忽略不计。
Unless the compiler somehow optimizes your code, declaring a variable inside a for loop will require the allocation of new variables and the collection of old ones. That being said, the compiler does a really good job at optimizing your code.
If you want a quick way to test your two scenarios, use the StopWatch class to measure how much time it takes to execute each case. My guess is that this difference will be nonexistent to negligible.