Jul 20

C# Alternative to a Type Dictionary

Somewhat recently, I needed a dictionary whose index was the entry’s type. The obvious way to go about this of course was to simply create a dictionary whose index was the entry’s type, like so:

ConcurrentDictionary<RuntimeTypeHandle, object> _typeDictionary;

There is a really cool, and much faster, alternative though – which was brought to my attention by one of the geniuses (Wil Bennett) I’m fortunate enough to work with every day. You can leverage C# Generics to accomplish exactly what the dictionary would. First, create this simple class that will function essentially like the type-indexed dictionary entry. I’m going to use an integer to function as the dictionary entry’s value in this example; you’d replace this with whatever value you’re interested in indexing.

private class Context<T>
{
       public static volatile int Value = 0;
}

Then, we need a method that will utilize our new class – something simple, just to show off how much faster it is relative to just using a Dictionary.

public void TimeClass<T>(int iterations)
{
       int value = 0;

       var watch = Stopwatch.StartNew();
       Context<int>.Value = 0;

       for (int i = 0; i < iterations; i++)
       {
              ++Context<T>.Value;
       }

       watch.Stop();
       value = Context<int>.Value;

       if (iterations <= 10)
              return;

       Console.WriteLine("Class        : Iterations: {0:N0}, Elapsed: {1}, Value: {2:N0}",
              iterations, watch.Elapsed, value);
}

Now, to test this, we can add a couple of additional methods that use the more conventional approaches to this problem.

public void TimeDictionary<T>(int iterations)
{
       var dict = new Dictionary<Type, int>();
       int value = 0;

       var watch = Stopwatch.StartNew();
       var type = typeof(T);

       for (int i = 0; i < iterations; i++)
       {
              if (!dict.TryGetValue(type, out value))
              {
                     value = 0;
                     dict[type] = value;
              }

              dict[type] = ++value;
       }

       watch.Stop();

       if (iterations <= 10)
              return;

       Console.WriteLine("Dictionary  : Iterations: {0:N0}, Elapsed: {1}, Value: {2:N0}",
              iterations, watch.Elapsed, value);
}

public void TimeDictionary2<T>(int iterations)
{
       var dict = new Dictionary<Type, object>();
       object value = 0;

       var watch = Stopwatch.StartNew();
       var type = typeof(T);

       for (int i = 0; i < iterations; i++)
       {
              if (!dict.TryGetValue(type, out value))
              {
                     value = 0;
                     dict[type] = value;
              }

              value = (int)value + 1;
              dict[type] = value;
       }

       watch.Stop();

       if (iterations <= 10)
              return;

       Console.WriteLine("Dictionary2: Iterations: {0:N0}, Elapsed: {1}, Value: {2:N0}",
              iterations, watch.Elapsed, value);
}

Lastly, throw it all together inside of Main(), then fire it up and test it.

using System;
using System.Threading;
using ININ.Messaging;

void Main()
{
       int iterations = 10;
       TimeDictionary<int>(iterations);
       TimeDictionary2<int>(iterations);
       TimeClass<int>(iterations);

       iterations = 10000000;
       TimeDictionary<int>(iterations);
       TimeDictionary2<int>(iterations);
       TimeClass<int>(iterations);
}

The results really are pretty impressive with regards to how much faster this approach is.

DictionaryTrickResults

Jan 30

AAPL Cash/Share

I’m not particularly a fan of Apple products, nor have I ever understood the willingness of consumers to pay a sizeable premium for them, but I can’t argue with Apple’s success as a company. Their annual EPS growth has been both absurdly consistent and absurdly high. Consumer sentiment might be shifting though, which of course would impact their profitability. Recently, I’ve started digging through their financial statements, to at least better understand whether I could justify some longer-term puts. Granted, I haven’t totally convinced myself on the bearish direction yet, but so far anyway it makes more sense. Between foundries demanding a larger cut, and rising Chinese wages due to the emergence of its middle class, I just don’t see how AAPL’s margins are maintainable – but again, I’ve admittedly never understood their consumer base. Nevertheless, in returning to the point of this post, it’s worth mentioning that as of their last financial statement, $145 of their ~$450 share price is accounted for solely through their immense cash reserves. Ben Graham might wait until it hits that price to move long on it (he might be waiting forever), but I’m thinking it looks interesting around $300 (I might also be waiting forever). I’ll have to wait and see if Mr. Market agrees.

AAPL January 23-24, 2013

Jan 30

When you want to succeed as bad as you want to breath, then you’ll be successful

I’ve already covered the best motivational video ever, but this might be the second best.

The original speech is by Eric Thomas. I might be a little biased on this one since we share first names. 🙂

Jan 12

CodeMash 2013 Dessert Bar

This was definitely one of the highlights.

CodeMash 2013 Desert Bar

Jan 10

CodeMash 2013

Well, I thought the highlight so far was Rob Gillen‘s use of a buffer overflow to get a command prompt with admin privileges in Windows 7. However, I just realized I’m sitting next to Jon Skeet in Evan Hauck’s presentation. Sorry Rob.

Jan 10

Really Good Personal Finance Blog

Brass Knuckle Finance is a refreshingly good blog I stumbled upon after following a link to its article on rap artists who are particularly “Frontin’ Ass.” Now, Frontin’ Ass, here, apparently means projecting an impossible facade of wealth given actual finances – which is a depressingly common behavior in general, and hardly unique to rap artists. Usually, this unrealistic lifestyle is financed through some form of debt. For rap artists, it might be their advance; for everyone else, it’s probably some other form of personal debt – credit cards are popular for instance. The folks over at Brass Knuckle Finance are vehemently opposed to any form of personal debt (especially credit card), and many of their articles espouse the benefits of – and offer advice for – living an altogether debt-free lifestyle.

One piece of advice they have is to simply get rid of your credit cards, but let’s dig into that some more. Similar to the guys above, I’m also against against credit card debt (for the most part); however, I’m very pro credit card. If you can manage to always pay off your statement balance within the grace period, then credit cards can be quite beneficial – particularly those with a reward component of some sort. I’m partial to the cash-back variety. Provided you’re never having to pay finance charges, penalties, or membership fees, you should always come out ahead by using cash-back credit cards.

Credit card debt is an entirely different animal though. Interest rates, often around 20%, are just stupidly exorbitant. So, unless you’re an investment pro – capable of returns in excess of 20% – it makes absolutely no sense to ever carry a balance at those rates. Occasionally though, you’ll encounter the promotional offers with rates of 0% for a period of time. As long as there isn’t a fee to take advantage of it (like there is with balance transfers), and you can pay it off in full before the expiry of the promotion, then you should always come out ahead.

These two caveats require a fair amount of discipline, and it’s for this reason that I believe they aren’t discussed over at Brass Knuckle. But, they can both work very much to your advantage if you can manage it. There’s a lot more I want to discuss about debt too. Debt-free is not necessarily the way to be if you know the spreads are in your favor, but this is a topic for another post. Debt-free is certainly less risky though, and for that reason the advice from Brass Knuckle might be preferred by the majority.

Jan 08

Jackie Chan Bollocks

You’ll find none of it in this class.

Jan 08

prettyPhoto Media

Being new to WordPress, I didn’t realize that Lightbox wasn’t the default for posted images, so I needed to add this support. I went with the prettyPhoto Media plugin to accomplish this for now. I found a few pages promoting the plugin, but they didn’t actually demonstrate how simple it was to use (notable exception).

Just link to the media file when adding your image.
Insert

Then, add the rel=”prettyPhoto” markup to the anchor tag it inserts (note that value “prettyPhoto” is actually configurable in this plugin, so it could be different if you changed that setting).
AddPost

Jan 07

Chris Christmas Rodriguez

A little late on this one, but I don’t want to wait until next December.

The rest of the videos are here, but they’re in QuickTime format. Unfortunately, when this ad campaign was run, he totally did not receive enough votes to replace Santa.

Jan 07

Best Craigslist Roommate Ad Ever!

I’m not sure how long this will remain on Craigslist, so I’ve included a screenshot for perpetuity.

Best Craigslist Roommate Ad

It’s not an ad for disguised weaponry, but it’s still pretty funny.

Older posts «

» Newer posts