I have two backgroundworkers that are calling one function in an infinite while loop but with different input parameters. There are a lot of variables used in that function.
Question: what is the best approach for defining the variables used inside the function?
If I define the variables globally, the performance is great. BUT, I must use lock a lot of times to make sure there is no conflicts when the variables are modified.
If I define the variables locally inside the function, there would be no conflict (obviously), but the code gets 2-3 times slower. This is as expected, because it is just like defining variables inside loop instead of defining them outside the loop.
One solution is to make another copy of that function and define separate global variables for use for the second thread and second function called in that thread. This may be good in terms of performance, but I believe it is not the most elegant approach.
Any opinion/solution is appreciated.
Create a Class that contains Properties for all the variables. Have each BackgroundWorker create their own instance of this class and pass it to the function as a Argument.
Although I'm not quite clear why your performance slows down 2-3 times if you define these variables in the Function itself.
Are the parameters from each Background Worker effectively "constant"? If so, you could create a function which returns a function - its similar to the solution you've come up with but more elegant because you don't actually need to make copies of the function. Here's a trivial example:
public void RunBackgroundWorkerOne()
{
var myFunction = CreateFunction("Hello ", "World");
while (true)
myFunction();
}
public Func<string> CreateFunction(string value1, string value2)
{
return (value1, value2) =>
{
return String.Format(value1, value2);
};
}
Then each background worker gets its own copy of the function built around the parameters that it wants to use.
Depending on how complex the parameters are for the function you're creating, you may want to create a "parameter map" type of class to make the code clearer.
Related
I tried to search for this but couldn't quite find an answer.
I have a method, and inside it there's a code block call very often, so I refactored it into a local Func.
Now because I don't use that code block anywhere else, it makes sense to have this instead of another method.
But is it better, performance-wise, to use another method? Does the Func get allocated or in some other way use extra processing time or memory because it's declared inside the function, or does it get cached or even actually made into a method behind the scenes by the compiler?
I know it sounds like a micro-optimization thing, but in my case, the method gets called very often. So maybe that changes the consideration.
So, basically:
public T CalledVeryOften(...)
{
Func<...> block = () => ...;
//code that calls 'block' several times
}
or
public T CalledVeryOften(...)
{
//code that calls 'block()' several times
}
private ... block()
{
...
}
Nah, there shouldn't be a huge difference in performance. A Func either compiles to a static or instance method depending on whether you use closures.
However, if you can inline the Func code it can increase performance.. maybe. Not sure how to do that though.
By inline, I'm referring to the inline keyword we can have in C++. It tells the compiler to embed the function instructions in that code block. I'm not sure if C# offers that benefit.
Btw, if the private method really belongs to a method block that can be reusable and you are using Func for the sake of performance increase, I'd refactor it back to the way it was.
It is a micro optimisation :) Unless your program is noticeably slowing down to an unacceptable level and profiling determines that the root cause is the fact you're making the function call, then you can consider alternatives.
The overhead really is negligible in the grand scheme of things. I would definitely file this under "Things I need not be concerned about".
Besides, you've probably made your code more readable in the process.
In C# it's conventional to write in a fairly objective manner, like so:
MyObj obj = new MyObj();
MyReturn ret = obj.DoSomething();
AnotherReturn rett = ret.DoSomethingElse();
I could just write the above like this:
AnotherReturn rett = new MyObj().DoSomething().DoSomethingElse();
However, how does the stackframe work when you have a bunch of function calls in a sequence like this? The example is fairly straightforward but imagine if I've got 50+ function calls chained (this can possibly happen in the likes of JavaScript (/w jQuery)).
My assumption was that, for each function call, a return address is made (to the "dot"?) and the return value (a new object with other methods) is then immediately pumped into the next function call at that return address. How does this work w.r.t. getting to the overall return value (in this example the return address will assign the final function value to rett)? If I kept chaining calls would I eventually overflow? In that case, is it considered wiser to take the objective route (at the cost of "needless" memory assignment?).
It's exactly the same as if you called each method on a separate line, assigning the return value to a variable each time and then using that variable to call the next method.
So your two samples are the same, effectively.
Do you have Reflector? You could try the two methods and inspect the generated IL code to see exactly what differences there are.
Although the 2 calls are same but if you have lot of "Dots" then somewhere it is a code smell (Law of Demeter).
See below discussion
I have a situation where I have to pass a List<> across 2-3 independent classes up and down the class. Right now I'm mostly passing the list using parameter so all 3 classes gets the list. Should I use a static list instead of passing List all over the classes to simplify the code like Class23.ListObjects.Add() and then release the static values once the operation is done so the next operation starts with an empty List. Right now it feels like the parameters are getting a lot and I'm getting confused if the list has the right values, forgetting to pass the list to the next class, etc. What do you think?
I would suggest you create a new class that represents the combined operation performed by the various classes (a "context" class, if you will). Values needed to perform the operation can be held as instance variables in that context, along with instances of the classes used in performing the work.
That way, you avoid passing stuff around (as code evolves, this can get somewhat ugly) while avoiding a "global" variable. Data is in exactly the scope it needs to be, and is disposed when the overall operation is complete.
In Coding practices, it is bad to have static or Global variables and passing through parameters is considered good.
If you use a static parameter, you run the risk of getting corrupted data if those functions are used in multiple places in your code, especially if threading is involved.
For instance, suppose Class A needs to use your functions that act on your static list. Before those functions are completed, Class B tries to use them as well, causing the list to get data from both calls, since the same static list is used in both cases.
I would like to be able to mark a function somehow (attributes maybe?) so that when it's called from anywhere, some other code gets to process the parameters and return a value instead of the called function, or can let the function execute normally.
I would use it for easy caching.
For example, if I had a function called Add10 and it would look like this:
int Add10 (int n)
{
return n + 10;
}
If the function go called repeatedly with the same value (Add10(7)) it would always give the same result (17) so it makes no sense to recalculate every time. Naturally, I wouldn't do it with functions as simple as this but I'm sure you can understand what I mean.
Does C# provide any way of doing what I want?
I need a way to mark a function as cached so that when someone does Add10(16) some code somewhere is ran first to check in a dictionary is we already know the Add10 value of 16 and return it if we do, calculate, store and return if we don't.
You want to memoize the function. Here's one way:
http://blogs.msdn.com/b/wesdyer/archive/2007/01/26/function-memoization.aspx
Instead of the function, then I would expose a Func<> delegate:
Func<int, int> add10 = (n) =>
{
// do some other work
...
int result = Add10(n); // calling actual function
// do some more perhaps even change result
...
return result;
};
And then:
int res = add10(5); // invoking the delegate rather than calling function
Like Jason mentioned, you probably want something like function memoization.
Heres another SO thread about it:
Whose responsibility is it to cache / memoize function results?
You could also achieve this sort of functionality using principles related to Aspect Oriented Programming.
http://msdn.microsoft.com/en-us/magazine/gg490353.aspx
Aspect Oriented Programming in C#
MbCache might be what you're looking for.
I am working with Asp.NET and I have a class named PathFinder which has methods like StyleBarPath(string BrandId,string ProductId) which returns for example a combination of path including brandId and productId and also there are such methods in the same class.
What I am thinking to make them static methods to invoke them easily in every where by saying PathFinder.StylePath("1","2"); to use the returned values inside a user control.
But since I am working too much these days, what I know is getting complicated for some reasons. Anyways, here is my question :
Since I am using inline coding on a lot of places like <a href='<%=PathFinder.StylePath("1","2")%>'></a>, I don't want to create a lot of instances by doing this <a href='<%=new PathFinder().StylePath("1","2")%>'></a> by declaring the methods not-static.
But I am afraid of changing the methods returns values because defining the methods static. I mean when a client calls this method, it wouldn't affect the other clients who invoke the same method at the same time?
They would have different call stacks right?
Lets say :
client one invokes the method with these parameters -- {brandId:2,productId:3}
client tow invokes the method with these parameters -- {brandId:3,productId:4}
This actions happens near the same time when the server processing their requests. What I want to learn is whether the invocations affect each others and change the returning values of each other since they are defined static.
Thanks for reading so far and being a helper :)
I just don't want the clients see path/1/2/ while they are waiting for path/2/3/
Some Notes about the question :
Is it the same for static fields?
You can call a static method safely from multiple threads simultaneously and at separate times given the following:
The static method does not access variables outside of itself, or those variables are also thread safe.
The static method does not create side effects which are not thread safe.
If your method is what it looks like it is, you're simply taking some inputs adjusting them and returning the result without accessing anything outside of the function. That would be completely safe.
Static fields are not the same as methods at all. It is one copy of a variable. Any changes to that static field will affect everything else that uses it.
In C#, static means (in layman's terms) there is one copy.
If you provide arguments to the method, and you return a value based on those parameters only, then you will be perfectly safe.
The only time you might run into problems is if your static method uses any static variables to store data between calls, since that could make call-1 change the value of call-2.
From the example you gave, you are safe.
As for your question about static fields, each caller can see the same static fields, since those are shared between instances. Keep that in mind while programming!
This should answer most of you questions
http://odetocode.com/Articles/313.aspx
As I understand it, static methods are thread safe, but not static properties