I have two questions, actually. But they are very closely related.
Suppose I have a simple struct
like this:
public struct TradePrice {
public float Price;
public int Quantity;
public TradePrice(float price, int quantity) {
Price = price;
Quantity = quantity;
}
}
Question 1
Now if I have code somewhere that needs to access these values, is there any difference between doing this:
TradePrice tp = new TradePrice(50.0f, 100);
And this:
float p = 50.0f;
int q = 100;
I feel like the first, since it is calling a constructor, should have something like the overhead of a method call. But that is just a guess.
Question 2
The answer to the above question actually probably answers this question as well, but perhaps there is some subtlety that makes these scenarios different; so I will ask anyway. Suppose I have a struct
which itself has members that are struct
types. Like this:
public struct BidAsk {
public TradePrice Bid;
public TradePrice Ask;
}
Then would there be any difference between these three methods?
Reset(TradePrice bid, TradePrice ask) {
Bid = bid;
Ask = ask;
}
Reset(float bidPrice, int bidQuantity, float askPrice, int askQuantity) {
Bid = new TradePrice(bidPrice, bidQuantity);
Ask = new TradePrice(askPrice, askQuantity);
}
Reset(float bidPrice, int bidQuantity, float askPrice, int askQuantity) {
Bid.Price = bidPrice;
Bid.Quantity = bidQuantity;
Ask.Price = askPrice;
Ask.Quantity = askQuantity;
}
I am inclined to think that there is some overhead to the constructor for a struct
, and so even though the same amount of data is being passed/set in the above methods, the first and last ones might be slightly more efficient. Is this true? And are the first and last methods even different?
For the record, I'm not asking this because I mistakenly believe this is contributing to a performance bottleneck or that it particularly matters from a design standpoint (though perhaps someone will surprise me by arguing that it does). I'm asking because I'm just curious.