C#,在for..loop中声明变量,会降低性能吗?

发布于 2024-12-11 17:31:40 字数 293 浏览 0 评论 0原文

例如:

            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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

拍不死你 2024-12-18 17:31:40

不,变量纯粹是为了程序员的方便。在哪里声明它们并不重要。请参阅我的回答这个重复的问题了解更多详细信息。

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.

物价感观 2024-12-18 17:31:40

也许你可以看看我曾经做过的关于另一次谈话的旧测试。 变量声明。优化方式

结果证明,重新定义速度更快,但内存不那么容易。

我的简单测试。我初始化了一个对象 100,000,000 次,创建一个新对象显然比重新使用旧对象更快:O

    string output = "";
    {
        DateTime startTime1 = DateTime.Now;
        myclass cls = new myclass();
        for (int i = 0; i < 100000000; i++)
        {
            cls = new myclass();
            cls.var1 = 1;
        }
        TimeSpan span1 = DateTime.Now - startTime1;
        output += span1.ToString();
    }

    {
        DateTime startTime2 = DateTime.Now;
        for (int i = 0; i < 100000000; i++)
        {
            myclass cls = new myclass();
            cls.var1 = 1;
        }
        TimeSpan span2 = DateTime.Now - startTime2;
        output += Environment.NewLine + span2.ToString() ;
    }
    //Span1 took 00:00:02.0391166
    //Span2 took 00:00:01.9331106

public class myclass
{
    public int var1 = 0;
    public myclass()
    {
    }
}

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 output = "";
    {
        DateTime startTime1 = DateTime.Now;
        myclass cls = new myclass();
        for (int i = 0; i < 100000000; i++)
        {
            cls = new myclass();
            cls.var1 = 1;
        }
        TimeSpan span1 = DateTime.Now - startTime1;
        output += span1.ToString();
    }

    {
        DateTime startTime2 = DateTime.Now;
        for (int i = 0; i < 100000000; i++)
        {
            myclass cls = new myclass();
            cls.var1 = 1;
        }
        TimeSpan span2 = DateTime.Now - startTime2;
        output += Environment.NewLine + span2.ToString() ;
    }
    //Span1 took 00:00:02.0391166
    //Span2 took 00:00:01.9331106

public class myclass
{
    public int var1 = 0;
    public myclass()
    {
    }
}
影子的影子 2024-12-18 17:31:40

我相信这将是一个性能问题。由于虚拟机需要分配内存来存储每个循环对字符串的引用。即使引用可能是同一个 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.

自找没趣 2024-12-18 17:31:40

更新:

如果您使用与循环相同类型的变量,您可以执行我最初建议的操作:

for (int  i = 0,  myvar = 0; i < 100; i++) {
    //some logic
}

否则不用担心,因为其他人已经建议了

@phoog,谢谢检查答案

UPDATE:

if your are using the same type of variable as the loop you could do what I originally sugested:

for (int  i = 0,  myvar = 0; i < 100; i++) {
    //some logic
}

otherwise don't worry about it as others already suggested

@phoog, thx for checking the answer

抚笙 2024-12-18 17:31:40

提供一个现实生活中的例子:

我刚刚写完一个 .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.

吹梦到西洲 2024-12-18 17:31:40

是的,这会产生内存使用问题。我不认为这会导致内存泄漏,因为垃圾收集器最终会收集未使用的对象,但这会对应用程序的性能产生负面影响。

我建议您使用在 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.

宁愿没拥抱 2024-12-18 17:31:40

它不会完全降低性能或导致内存泄漏,但仍然需要小心。

字符串是不可变的,这意味着一旦创建,就无法更改。通过在循环内创建新字符串,您将创建至少 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.

淡淡の花香 2024-12-18 17:31:40

除非编译器以某种方式优化您的代码,否则在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文