Declaring a disposable object: inside or outside a loop? - c#

Should I use using block inside a loop or outside of it? Is there any sensible performance difference? Is there any difference in the case of Graphics object? While the second approach may seem better, the while could be a long block and make the code less readable.
while (i < 100)
{
using(Graphics g = Graphics.FromImage(bitmap)
{
g.DrawImage(...);
}
}
vs.
using(Graphics g = Graphics.FromImage(bitmap)
{
while (i < 100) // a long while block
{
// I may use other functions such as g.DrawLine .. or g.DrawText ...
// Moreover while could be a long block
g.DrawImage(...);
}
}

Unless you're using a different Bitmap for each loop, you should put the using block outside of it.

As a rule of thumb, place the using inside the loop if you plan to use the object only once OR the object is not designed to be reused (SQLCommand class comes to mind as an example). Otherwise place it outside the loop.
In your specific case, if your intent is to draw the same image 100 times, then outside the loop is the way to go. On the other hand, if your intent is to draw 100 distinct images inside a loop, then the only way it could work would be to place the using inside the loop, because the Graphics object cannot be reused with another image.

in terms of performance outside of the while loop so you don't have to make 100 objects. It might depend how you want to manage exceptions though.

Given the sample code, I would absolutely go for the second option and put the loop inside the using. Far better performance that way.
If there's additional logic that is changing which bitmap you are using in the middle of the loop, you may need to consider the first option. Just be aware that you will likely suffer a performance hit.

Related

C# XNA - I want to access the Board(instance of a class) that this particular Block(instance of a class) exists in

I thought about it for a long time, and I couldn't come up with a better title. I'm not sure what specific thing I need to figure out in order to solve this problem. This is the code I have minus anything I think is unnecessary for this question.
static class GameManager
{
public static List<Board> Boards = new List<Board>();
// let's say there are 2 boards
}
class Board
{
public Dictionary<Vector2, Block> Blocks = new Dictionary<Vector2, Block>();
//each board has a bunch of blocks in it.
{
class Block
{
//I want to access the Board that this particular Block exists in.
}
See, I used to have just one board, so if I was a block in the block class, and I wanted to access, say, the number of blocks in a board, I could just use GameManager.Board.Blocks.Count. I wanted to add multiplayer, so I made a list of boards each with their own set of blocks. Now I need to somehow make a block know which board it's in.
Is there maybe a way I can go backwards in terms of accessing different levels of code? For example, if I started at GameManager, I could go forward through levels by saying GameManager.Boards[0].Blocks[new Vector2(0, 0)] with a . for every level I go down. If I'm starting at the Block class, am I able to go up to access the particular instance of Board that the current instance of Block exists within? I don't want to turn this into an XY problem so what do you think I should do? It seems like storing and passing a variable that keeps track of the current board that's being updated is sloppy code because each block should already know which board it exists in since I did in fact initiate multiple boards each containing their own separate set of blocks. Do you think perhaps I need to nest the Block class within the Board class?
Given your design, there is no direct way for a block to know which board its in. In general, this is a good thing. Why would a block need any knowledge of its board?
But, you could write this (as is):
var parent = GameManager.Boards.FirstOrDefault(b => b.Blocks.Values.Contains(this));
Now that's pretty inefficient, and not very pretty. You could also just pass the board to the block when you create it and hold it in a parent field of the Block class. This is much more speed efficient, at the cost of an extra variable per block.
In reality though, classes rarely if ever need to know about what is holding them. Think carefully to determine if this is actually a requirement for your game.

How to effectively discard an array and fill it with new values?

I've got a few global arrays I use in a simple WinForms game. The arrays are initialized when a new game starts. When a player is in the middle of the game (the arrays are filled with data) he clicks on the StartNewGame() button (restarts the game). What to do next?
Is it ok to reinitialize the whole array for the new game or should I just set every array item to null and use the already initialized array (which would be slower)?
I mean is it okay to do something like this?
MyClass[,] gameObjects;
public Form1()
{
StartNewGame();
// game flow .. simplified here .. normally devided in functions and events..
StartNewGame();
// other game flow
}
public StartNewGame()
{
gameObjects = new MyClass[10,10];
// some work with gameObjects
}
This almost entirely depends upon MyClass, specifically how many data members it contains, how much processing does its constructor (and members' constructors) require and whether it is a relatively simply operation to (re)set an object of this class to "initialized" state. A more objective answer can be obtained through benchmarking.
From you question, I understand that there are not so many array's - in that case I would say, reinitialize the whole array
In cases you have a lot of work that can take 30 sec to set up maybe you do clean up instead of reinitializing everything.
If you choose to place null, you can jet some ugly exception , so I think you rather clean the object inside the array rather then set them to null
If there are only 100 elements as in your example, then there shouldn't really be a noticeable performance hit.
If you reinitialize the array, you will perform n constructions for n objects. The garbage collector will come clean up the old array and de-allocate those old n objects at some later time. (So you have n allocations upfront, and n deallocations by the GC).
If you set each pointer in the array to null, the garbage collector will still do the same amount of work and come clean up those n objects at some later time. The only difference is you're not deallocating the array here, but that single deallocation is negligible.
From my point of view, the best way to achieve performance in this case is to not reallocate the objects at all, but to use the same ones. Add a valid bit to mark whether or not an object is valid (in use), and to reinitialize you simply set all the valid bits to false. In a similar fashion, programs don't go through and write 0's to all your memory when it's not in use. They just leave it as garbage and overwrite data as necessary.
But again, if your number of objects isn't going into the thousands, I'd say you really won't notice the performance hit.
gameObjects = new MyClass[10,10];
... is the way to go. This is definitely faster than looping through the array and setting the items to null. It is also simpler to code and to understand. But both variants are very fast in anyway, unless you have tens of millions of entries! '[10, 10]' is very small, so forget about performance and do what seems more appropriate and more understandable to you. A clean coding is more important than performance in most cases.

Best practice for creating objects used in for/foreach loops

What's the best practice for dealing with objects in for or foreach loops? Should we create one object outside the loops and recreate it all over again (using new... ) or create new one for every loop iteration?
Example:
foreach(var a in collection)
{
SomeClass sc = new SomeClass();
sc.id = a;
sc.Insert();
}
or
SomeClass sc = null;
foreach(var a in collection)
{
sc = new SomeClass();
sc.id = a;
sc.Insert();
}
Which is better?
The first way is better as it more clearly conveys the intended scope of the variable and prevents errors from accidentally using an object outside of the intended scope.
One reason for wanting to use the second form is if you want to break out of the loop and still have a reference to the object you last reached in the loop.
A bad reason for choosing the second form is performance. It might seem at first glance that the second method uses fewer resources or that you are only creating one object and reusing it. This isn't the case here. The repeated declaration of a variable inside a loop doesn't consume any extra resources or clock cycles so you don't gain any performance benefit from pulling the declaration outside the loop.
First off, I note that you mean "creating variables" when you say "creating objects". The object references go in the variables, but they are not the variables themselves.
Note that the scenario you describe introduces a semantic difference when the loop contains an anonymous function and the variable is a closed-over outer varible of the anonymous function. See
http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/
for details.
I'm sure someone might whip out the MSIL analysis, but practically there is no discernible difference in execution or performance. The only thing you're affecting is the storage of an object reference.
I say keep it clean and simple; declare the variable inside the loop. This provides the open/closed principle in practice, so you know the scope the variable is used and is not reused elsewhere. On the next loop, the variable loses scope and is reinitialized automatically.
You are creating a new object in each loop iteration in both cases (since you call new SomeClass()).
The former approach makes it clear that sc is only used inside the loop, which might be an advantage from a maintenance point of view.
I think it does not matter for performance, but I prefer the first one. I always try to keep declaration and instantiation together if possible.
I would go with option 2 to be tidy, to keep all declarations in one place.
You may say that
"objects should only be declared where and when they are needed"
but your loop would probably be in its own little method.
I would use the first one, but for compiler it is the same, because compiler moves out declaration of variables from the loops. I bet after compiling the code would look like second one.

Safely iterate an array that can be changed in another thread

I want to safely iterate(not get a collection was changed during iteration) through an array that can be changed by another thread.
What's the best way I can do it?
What do you mean by "safely"? Do you mind seeing a mixture of old and new values? If so, you can just iterate using foreach. (This is for two reasons: firstly, arrays don't have an internal "version number" like List<T> does, so the iterator can't detect that the array has changed. Secondly, using foreach on a type known to be an array in C# causes the compiler to use the length and indexer anyway, rather than using an iterator.)
If you want to get a snapshot, you basically need to take a copy of the array and iterate over that.
EDIT: I was assuming you wanted concurrency. (I'm not sure why I assumed that.) I agree with the other answers that locking is an alternative - but you need to lock around the whole iteration, e.g.
lock (someLock)
{
foreach (var x in array)
{
// Stuff
}
}
and likewise in the writing thread:
lock (someLock)
{
array[0] = "foo";
}
(You could lock on the array itself, but I generally prefer to have private locks.)
Make a copy? I guess it depends on whether you want your iteration to be a 'snapshot in time' or if you want to see the changes 'live'. The latter can get pretty dicey.
Target 4.0 and use one of the many thread safe collections.
You probably want to use syncronized access. You can lock the array for the time you need to parse it and the time you add/remove items.
You could use lock/unlock (http://msdn.microsoft.com/en-us/library/c5kehkcz(VS.80).aspx
For ultra safeness, you could lock all access to the array while you are iterating through it. Its the only way to ensure that the array you are iterating through is fully up to date..

Using foreach (...) syntax while also incrementing an index variable inside the loop

When looking at C# code, I often see patterns like this:
DataType[] items = GetSomeItems();
OtherDataType[] itemProps = new OtherDataType[items.Length];
int i = 0;
foreach (DataType item in items)
{
// Do some stuff with item, then finally
itemProps[i] = item.Prop;
i++;
}
The for-loop iterates over the objects in items, but also keeping a counter (i) for iterating over itemProps as well. I personally don't like this extra i hanging around, and instead would probably do something like:
DataType[] items = GetSomeItems();
OtherDataType[] itemProps = new OtherDataType[items.Length];
for (int i = 0; i < items.Length; i++)
{
// Do some stuff with items[i], then finally
itemProps[i] = items[i].Prop;
}
Is there perhaps some benfit to the first approach I'm not aware of? Is this a result of everybody trying to use that fancy foreach (...) syntax? I'm interested in your opinions on this.
If you are using C# 3.0 that will be better;
OtherDataType[] itemProps = items.Select(i=>i.Prop).ToArray();
With i being outside the array then if would be available after the completion of the loop. If you wanted to count the number of items and the collection didn't provide a .Count or .UBound property then this could be useful.
Like you I would normally use the second method, looks much cleaner to me.
In this case, I don't think so. Sometimes, though, the collection doesn't implement this[int index] but it does implement GetEnumerator(). In the latter case, you don't have much choice.
Some data structures are not well suited for random access but can be iterated over very fast ( Trees, linked lists, etc ). So if you need to iterate over one of these but need a count for some reason, your doomed to go the ugly way...
Semantically they may be equivalent, but in fact using foreach over an enumerator gives the compiler more scope to optimise.
I don't remember all the arguments off the top of my head,but they are well covered in Effective C#, which is recommended reading.
foreach (DataType item in items)
This foreach loop makes it crystal clear that you're iterating over all the DataType item of, well yes, items. Maybe it makes the code a little longer, but it's not a "bad" code. For the other for-loop, you need to check inside the brackets to have an idea for what this loop is used.
The problem with this example lies in the fact that you're iterating over two different arrays in the same time which we don't do that often.. so we are stuck between two strategies.. either we "hack a bit" the fancy-foreach as you call it or we get back on the old-not-so-loved for(int i = 0; i ...). (There are other ways than those 2, of course)
So, I think it's the Vim vs Emacs things coming back in your question with the For vs Foreach loop :) People who like the for(), will say this foreach is useless, might cause performance issues and is just big. People who prefere foreach will say something like, we don't care if there's two extra line if we can read the code and maintenance it easily.
Finally, the i is outside the scope first the first example and inside for the second.. reasons to that?! Because if you use the i outside of your foreach, I would have called differently. And, for my opinion, I prefer the foreach ways because you see immediately what is happening. You also don't have to think about if it's < or =. You know immediately that you are iterating over all the list, However, sadly, people will forget about the i++ at the end :D So, I say Vim!
Lets not forget that some collections do not implement a direct access operator[] and that you have to iterate using the IEnumerable interface which is most easily accessed with foreach().

Categories