使用性能和使用性能 [英] Using properties and performance

查看:160
本文介绍了使用性能和使用性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在优化我的code和我注意到,使用属性(甚至自动属性)对执行时间产生深远的影响。请参见下面的例子:

I was optimizing my code, and I noticed that using properties (even auto properties) has a profound impact on the execution time. See the example below:

[Test]
public void GetterVsField()
{
    PropertyTest propertyTest = new PropertyTest();
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();
    propertyTest.LoopUsingCopy();
    Console.WriteLine("Using copy: " + stopwatch.ElapsedMilliseconds / 1000.0);

    stopwatch.Restart();
    propertyTest.LoopUsingGetter();
    Console.WriteLine("Using getter: " + stopwatch.ElapsedMilliseconds / 1000.0);
    stopwatch.Restart();
    propertyTest.LoopUsingField();
    Console.WriteLine("Using field: " + stopwatch.ElapsedMilliseconds / 1000.0);
}

public class PropertyTest
{
    public PropertyTest()
    {
        NumRepet = 100000000;
        _numRepet = NumRepet;
    }

    int NumRepet { get; set; }
    private int _numRepet;
    public int LoopUsingGetter()
    {
        int dummy = 314;
        for (int i = 0; i < NumRepet; i++)
        {
            dummy++;
        }
        return dummy;
    }

    public int LoopUsingCopy()
    {
        int numRepetCopy = NumRepet;
        int dummy = 314;
        for (int i = 0; i < numRepetCopy; i++)
        {
            dummy++;
        }
        return dummy;
    }

    public int LoopUsingField()
    {
        int dummy = 314;
        for (int i = 0; i < _numRepet; i++)
        {
            dummy++;
        }
        return dummy;
    }
}

发布在我的机器上的方式获取:

In Release mode on my machine I get:

Using copy: 0.029
Using getter: 0.054
Using field: 0.026 

这于我而言是一场灾难 - 最关键的循环就不能使用任何属性,如果我想获得最大的性能。

which in my case is a disaster - the most critical loop just can't use any properties if I want to get maximum performance.

我在做什么错在这里?我在想,这将是内联 JIT优化

推荐答案

按照80/20法则的表现,而不是微观优化。 写入,而不是性能code可维护性。 也许汇编语言是最快的,但是,这并不意味着我们应该用汇编语言用于所有目的。

Follow the 80/20 performance rule instead of micro-optimizing. Write code for maintainability, instead of performance. Perhaps Assembly language is the fastest but that does not mean we should use Assembly language for all purposes.

您正在运行的循环了100万次,差异为0.02毫秒或20微秒。调用一个函数将有一些开销,但在大多数情况下,也没有关系。你可以信任编译器内联或做先进的东西。

You are running the loop 100 million times and the difference is 0.02 millisecond or 20 microseconds. Calling a function will have some overhead but in most cases it does not matter. You can trust the compiler to inline or do advanced things.

直接访问该领域将是有问题的99%的情况下,你不会有您所有的变量都引用了在固定的地方太多的控制权,当你发现什么是错的。

Directly accessing the field will be problematic in 99% of the cases as you will not have control of where all your variables are referenced and fixing at too many places when you find something is wrong.

这篇关于使用性能和使用性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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