Getting Dictionary<K,V> from ConcurrentDictionary<K,V> in .NET 4.0 - collections

I'm parallelizing some back-end code and trying not to break interfaces. We have several methods that return Dictionary and internally, I'm using ConcurrentDictionary to perform Parallel operations on.
What's the best way to return Dictionary from these?
This feels almost too simple:
return myConcurrentDictionary.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
I feel like I'm missing something.

Constructing the Dictionary<K,V> directly will be slightly more efficient than calling ToDictionary. The constructor will pre-allocate the target dictionary to the correct size and won't need to resize on-the-fly as it goes along.
return new Dictionary<K,V>(myConcurrentDictionary);
If your ConcurrentDictionary<K,V> uses a custom IEqualityComparer<K> then you'll probably want to pass that into the constructor too.

Nope. This is completely fine. .NET sequences are just nice like that. :D

Related

Where did LoaderService go?

Upgrading AngleSharp from 0.9.6 to 0.9.9 I have this line of code no longer compiling:
return configuration.With(LoaderService(new[] { requester }));
It complains that LoaderService does not exist in the current context. So what happened to LoaderService? Is there a replacement? Does it still exist but just somewhere else?
Good question. Sorry for being late to the party, but even though you may have solved your problem someone else is having a hard time figuring it out.
LoaderService was essentially just a helper to create a loader. But having a service for anything creating a little thing would be overkill and not scale much. Also AngleSharp.Core would need to define all these. So, instead a generic mechanism was introduced, which allows registering such "creator services" via Func<IBrowsingContext, TService>.
However, to solve your piece of code I guess the following line would do the trick:
return configuration.WithDefaultLoader(requesters: requester);
This registers the default loader creator services (one for documents, one for resources inside documents) with the default options (options involve some middleware etc.).
Under the hood (besides some other things) the following is happening:
// just one example, config.Filter is created based on the passed in options
return configuration.With<IDocumentLoader>(ctx => new DocumentLoader(ctx, config.Filter));

Newbie trying to use Moq for enumerable method

I'm trying to see if Moq is something I'd like to use in a new project as the other mocking frameworks I've used are challenging IMHO. So for instance, I have a method as such:
IEnumerable<PickList> GetPickLists();
I'm not sure how I'm supposed to mock this... I've tried something like this, but I'm getting compliation errors (I know the following
Returns() isn't correct, but can't figure out what to put in the Returns body:
var mockCrm = new Mock<ICrmProvider>();
mockCrm.Setup<IEnumerable<PickList>>(foo => foo.GetPickLists())
.Returns<IEnumerable<PickList>>({});
Also, trying to mock something like these two methods:
CustomerSyncResult ApplyActions(IEnumerable<CustomerAction> actions);
IEnumerable<Customer> GetCustomers(IEnumerable<string> crmIDs, IEnumerable<string> emails);
I know I'm asking a blanket question, but I'm having a heck of a time getting started. The CHM in the download doesn't have enough samples for me and some of the tutorials out there seem to be using obsolete methods as well as not covering enumerations which makes it tricky for me :(
Any tips would be greatly appreciated.
Try
mockCrm.Setup(x => x.GetPickLists())
.Returns(new List<PickList>());
The QuickStart is a good reference.
Some examples for the other methods:
mockCrm.Setup(x => x.ApplyActions(It.IsAny<IEnumerable>()))
.Returns(new CustomerSyncResult());
mockCrm.Setup(x => x.GetCustomers(It.IsAny<IEnumerable>(),
It.IsAny<IEnumerable>()))
.Returns(new List<Customers>());
As an aside, make the IEnumerable generic in your original interface for better type safety.
You can also use the new Moq v4 functional specifications:
var list = new List<PickList> { new PickList() };
ICrmProvider crm =
Mock.Of<ICrmProvider>(
x =>
x.GetPickLists() == list);
That is not as well documented currently. Note that you no longer have to write mock.Object. Some links:
Old style imperative mocks vs moq functional specifications
Moq Discussions: Mock.Of - how to specify behavior?
The exact syntax (using It.Is, the contents of the lists, etc.) will depend on what you're trying to accomplish. It.IsAny will match any argument, which will make things easier when dealing with sequence or collection parameters.

Lambda expression is slower than foreach statement?

I did a small experiment to test whether lamdba expression can retrieve faster results than foreach statement. but, Lambda failed
System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch();
st.Start();
List<int> lst = new List<int>();
foreach (GridViewRow item in GridView1.Rows)
{
if (((CheckBox)item.FindControl("Check")).Checked)
{
lst.Add(Convert.ToInt32(((Label)item.FindControl("Id")).Text));
}
}
st.Stop();
Response.Write(st.Elapsed.ToString());
Response.Write("<br/><br/><br/>");
st.Reset();
st.Start();
List<int> lstRank = GridView1.Rows.OfType<GridViewRow>().Where(s => ((CheckBox)s.FindControl("Check")).Checked)
.Select(s => Convert.ToInt32(((Label)s.FindControl("Id")).Text)).ToList();
st.Stop();
Response.Write(st.Elapsed.ToString());
int i = 0;
output
00:00:00.0000249
00:00:00.0002464
why lambda is slower than foreach. This may be a drawback of lambda expression
Technically your 2 approaches are not identical. There are a few differences such as the use of "OfType" which is filtering the collection before continuing. You'd be better using "Cast<GridViewRow>()" as you know each element is of type GridViewRow.
Also, do you really need the expense of the ToList() at the end of the Linq statement as your linq query is now ready to iterate over and execute rather than having to convert back to a list?
There is a small overhead with lambda expressions because they are "compiled" at runtime. I think that's what you see in your "benchmark". for each ... is a fully compiled statement.
You can precompile lambda expressions. Look here. Maybe you want to rework your code and test again.
I won't talk about the correctness of your code but I'd like to get a chance to explain a general rule
In Software Develpment the performance loss is inversely proportional to the level of abtsraction.
In this case in quite normal that foreach is faster then LINQ (which is more abstract).
If you compare it with the classic for (for (int i:i++l,etc..) ) it will be faster than the foreach.
Access an object thought an interface is slower then access the concrete object : the interface is already a very small level of abstraction.
The code you write will be as much fast as it is "close" to the machine language but of course it will be less readable and maintainable.
The matter is how to find the right level of abstraction for what we are developing keeping an eyes on the performance and the code readability.
You won't need MVC pattern for making a one-page web site that shows a table on a Repeater :-)

How do you like to define your module-wide variables in drupal 6?

I'm in my module file. I want to define some complex variables for use throughout the module. For simple things, I'm doing this:
function mymodule_init() {
define('SOME_CONSTANT', 'foo bar');
}
But that won't work for more complex structures. Here are some ideas that I've thought of:
global:
function mymodule_init() {
$GLOBALS['mymodule_var'] = array('foo' => 'bar');
}
variable_set:
function mymodule_init() {
variable_set('mymodule_var', array('foo' => 'bar'));
}
property of a module class:
class MyModule {
static $var = array('foo' => 'bar');
}
Variable_set/_get seems like the most "drupal" way, but I'm drawn toward the class setup. Are there any drawbacks to that? Any other approaches out there?
I haven't seen any one storing static values that are array objects.
For simple values the drupal way is to put a define in the begining of a modules .module file. This file is loaded when the module is activated so that is enough. No point in putting it in the hook_init function.
variable_set stores the value in the database so don't run it over and over. Instead you could put it in your hook_install to define them once. variable_set is good to use if the value can be changed in an admin section but it's not the best choice to store a static variable since you will need a query to fetch it.
I think all of those methods would work. I have never used it in this fashion, but I believe the context module (http://drupal.org/project/context) also has its own API for storing variables in a static cache. You may want to check out the documentation for the module.
It's always a good practice to avoid globals. So that makes your choice a bit easier.
If you err towards a class, you'll be writing code that is not consistent with the D6 standards. There are a lot of modules that do it but I personally like to keep close to the Drupal core so I can understand it better. And code that's written in different styles through the same application can have an adverse effect on productivity and maintenance.
variable_set() and define() are quite different. Use the former when you can expect that information to change (a variable). Use the latter for constants. Your requirements should be clear as which one to use.
Don't worry too much about hitting the database for variable_set/get. If your software is written well, it should not effect performance hardly at all. Performance work arounds like that should only be implemented if your applications has serious performance issues and you've tried everything else.

When I want one object out of an firebaselistobservable using rxjs, should I still use subscribe?

I am kind of confused about which methods belong with and when to use them.
Right now, I am using subscribe for basically everything and it is not working for me when I want a quick static value out of Firebase. Can you explain when I should use subscribe vs other methods other than for a strict observable?
When working with async values you have a few options: promises, rxjs, callbacks. Every option has its own drawbacks.
When you want to retrieve a single async value it is tempting to use promises for their simplicity (.then(myVal => {})). But this does not give you access to things like timeouts/throttling/retry behaviour etc. Rx streams, even for single values do give you these options.
So my recommendation would be, even if you want to have a single value, to use Observables. There is no async option for 'a quick static value out of a remote database'.
If you do not want to use the .subscribe() method there are other options which let you activate your subscription like .toPromise() which might be easier for retrieving a single value using Rx.
const getMyObjPromise = $firebase.get(myObjId)
.timeout(5000)
.retry(3)
.toPromise()
getMyObjPromise.then(obj => console.log('got my object'));
My guess is, that you have a subscribe method that contains a bunch of logic like it was a ’.then’ and you save the result to some local variable.
First: try to avoid any logic inside the subscription-method -> use stream-operators before that and then subscribe just to retrieve the data.
You much more flexible with that and it is much easier to unit-test those single parts of your stream than to test a whole component in itself.
Second: try to avoid using a manual subscriptions at all - in angular controllers they are prone to cause memory leaks if not unsubscribed.
Use the async-pipe instead in your template and let angular manage the subscription itself.

Resources