Is instantiating a new Rectangle repeatedly slower than changing all its fields?
Currently I have this code:
selectorRect.X = (e.X + hscTileset.Value) / tileLayer.TileSize * tileLayer.TileSize;
selectorRect.Y = (e.Y + vscTileset.Value) / tileLayer.Ti开发者_运维百科leSize * tileLayer.TileSize;
selectorRect.Width = 32;
selectorRect.Height = 32;
I am just changing all of the rectangle's fields. What if I did something like this?
selectorRect = new Rectangle((e.X + hscTileset.Value) / tileLayer.TileSize * tileLayer.TileSize, (e.Y + vscTileset.Value) / tileLayer.TileSize * tileLayer.TileSize, 32, 32)
I know the second line is a lot longer and less readable and generally not recommended but I'm still curious over the speed differences or its effects on the stack or heap. Since this code is within a control's MouseMove event handler it is called quite often and I'm wondering whether or not instantiating a new object that often will cause considerable speed differences.
Thanks!
If I had to guess, then since this is a struct
I would expect them to be about the same. I would prefer the second ("new ...") for semantic reasons though - plus the first wouldn't work for a property (only a field/variable/array-lookup).
To get an exact measure : profile it in your context. I honesty doubt this will be a decision that makes a noticeable difference.
精彩评论