Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

Do methods within structs negatively affect memorysize or performance in C#?

Introduction to the goal:

I am currently trying to optimize performance and memory usage of my code. (mainly Ram bottleneck)

The program will have many instances of the following element at the same time. Especially when historic prices should be processed at the fastest possible rate. The struct looks like this in it's simplest way:

public struct PriceElement
{
    public DateTime SpotTime { get; set; }
    public decimal BuyPrice { get; set; }
    public decimal SellPrice { get; set; }
}

I realized the performance benefits of using the struct just like an empty bottle and refill it after consumption. This way, I do not have to reallocate memory for each single element in the line.

However, it also made my code a little more dangerous for human errors in the program code. Namely I wanted to make sure that I always update the whole struct at once rather than maybe ending up with just an updated sellprice and buyprice because I forgot to update an element.

The element is very neat like this but I have to offload methods into functions in another classes in order to have the functionality I require - This in turn would be less intuitive and thus less preferable in code.

So I added some basic methods which make my life a lot easier:

public struct PriceElement
{
    public PriceElement(DateTime spotTime = default(DateTime), decimal buyPrice = 0, decimal sellPrice = 0)
    {
        // assign datetime min value if not happened already
        spotTime = spotTime == default(DateTime) ? DateTime.MinValue : spotTime;
        this.SpotTime = spotTime;
        this.BuyPrice = buyPrice;
        this.SellPrice = sellPrice;

    }
    // Data
    public DateTime SpotTime { get; private set; }
    public decimal BuyPrice { get; private set; }
    public decimal SellPrice { get; private set; }
    // Methods
    public decimal SpotPrice { get { return ((this.BuyPrice + this.SellPrice) / (decimal)2); } }
    // refills/overwrites this price element
    public void UpdatePrice(DateTime spotTime, decimal buyPrice, decimal sellPrice)
    {
        this.SpotTime = spotTime;
        this.BuyPrice = buyPrice;
        this.SellPrice = sellPrice;
    }
    public string ToString()
    {
        System.Text.StringBuilder output = new System.Text.StringBuilder();
        output.Append(this.SpotTime.ToString("dd/MM/yyyy HH:mm:ss"));
        output.Append(',');
        output.Append(this.BuyPrice);
        output.Append(',');
        output.Append(this.SellPrice);
        return output.ToString();
    }
}

Question:

Let's say I have PriceElement[1000000] - will those additional methods put additional strain on the system memory or are they "shared" between all structs of type PriceElement?

Will those additional methods increase the time to create a new PriceElement(DateTime, buy, sell) instance, respectively the load on the garbage collector?

Will there be any negative impacts, I have not mentioned here?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

will those additional methods put additional strain on the system memory or are they "shared" between all structs of type PriceElement?

Code is shared between all instances. So no additional memory will be used.

Code is stored separately from any data, and the memory for the code is only dependent on the amount of code, not how many instance of objects there are. This is true for both classes and structs. The main exception is generics, this will create a copy of the code for each type combination that is used. It is a bit more complicated since the code is Jitted, cached etc, but that is irrelevant in most cases since you cannot control it anyway.

I would recommend making your struct immutable. I.e. change UpdatePrice so it returns a new struct instead of changing the existing one. See why is mutable structs evil for details. Making the struct immutable allow you to mark the struct as readonly and that can help avoid copies when passing the struct with an in parameter. In modern c# you can take references to structs in an array, and that also helps avoiding copies (as you seem to be aware of).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...