Ayende @ Rahien

Hi!
My name is Oren Eini
Founder of Hibernating Rhinos LTD and RavenDB.
You can reach me by phone or email:

ayende@ayende.com

+972 52-548-6969

, @ Q c

Posts: 18 | Comments: 72

filter by tags archive

Not all objects are created equals

time to read 1 min | 126 words

I found something extremely surprising while profiling a project. Take a look at this piece of code:

Stopwatch stop = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
	new WeakReference(null);
}
stop.Stop();
Console.WriteLine("WeakRef: " + stop.ElapsedMilliseconds);

stop = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
	new string('a', 5);
}
stop.Stop();
Console.WriteLine("'aaaaa': " + stop.ElapsedMilliseconds);

On my machine, this has the following output:

WeakRef: 980
'aaaaa': 35

Creating a WeakReference is much more costly than creating a normal object. Not surprising, when you think of it, WeakReference has deep ties to the CLR, but I couldn't really believe it when I saw it the first time.


Comments

Yitzchok

Isn't the object created equally it just depends on the amount of work done in the Constructor (ctor)?

Damien Guard

The constructor for WeakReference makes a call to GCHandle, which makes an extern call. The result of which is ~0.000850ms difference.

Why is it surprising? Do all your objects with constructors create in exactly the same amount of time?

[)amien

Ayende Rahien

Run it in a profiler, you'll see where that cost is

Ken Egozi

not sure, but due to the immutability of string, it might've created a single 'aaaaa' object.

did you try to call i.ToString() instead? (would new a string so it's quite the same). or, new string('a', i) ?

Ayende Rahien

Ken,

It doesn't matter what string you are using, or whatever you create another type

Bill Pierce

Are you sure that string interning doesn't have something to do with the performance of the string test?

Ayende Rahien

Try it with date time, or your own class

Comment preview

Comments have been closed on this topic.

FUTURE POSTS

  1. RavenDB 3.0 New Stable Release - 13 hours from now
  2. Production postmortem: The industry at large - about one day from now
  3. The insidious cost of allocations - 3 days from now
  4. Buffer allocation strategies: A possible solution - 6 days from now
  5. Buffer allocation strategies: Explaining the solution - 7 days from now

And 3 more posts are pending...

There are posts all the way to Sep 11, 2015

RECENT SERIES

  1. Find the bug (5):
    20 Apr 2011 - Why do I get a Null Reference Exception?
  2. Production postmortem (10):
    01 Sep 2015 - The case of the lying configuration file
  3. What is new in RavenDB 3.5 (7):
    12 Aug 2015 - Monitoring support
  4. Career planning (6):
    24 Jul 2015 - The immortal choices aren't
View all series

RECENT COMMENTS

Syndication

Main feed Feed Stats
Comments feed   Comments Feed Stats