Performance problem while adding entities using Mindscape Lightspeed

Mindscape Lightspeed provides a database layer for .NET programming. This article states that in some cases, using Attach() instead of Add() to add objects to the database can be significantly faster.

Add() is slow

To add an entity to a table, you typically create a new instance and make Lightspeed aware of it using

UnitOfWork.Add(entity);

When adding many entities, this method can be relatively slow. So slow in fact, that it takes up most of the time. This profiling tree shows that Entity.Add takes more than 50% of the time when adding many entities:

Profiling shows that Entity.Add takes more than 50% of the time when adding many entities

Why is Add() slow?

The Add() method checks whether the entity is really a new entity. Adding an object which was earlier retrieved from the database is an error. If the EntityState of the added object is not EntityState.New, the Add method throws an exception. That exception is retrieved from the embedded resources.

This functionality is implemented in an assertion, like this:

Invariant.ArgumentAssertion(
    entity.EntityState == EntityState.New,
    Resources.get_ExpectedEntityStateNew(), 
    "entity"
);

This differs from a normal if statement in that all parameters are evaluated. This means that every time you add an entity, the error message is retrieved from the resources. This is quite slow.

Alternative

An alternative to Add() is the Attach() method. The Attach() method does not do this check, and still adds the entity to the database. Switching from Add() to Attach() results in an improvement of 10 times in execution time.