Don't be afraid to create objects
The
question came up today, how expensive it is to create objects in .Net, and is
it worth keeping them in the cache if we can just as easily reconstruct them?
I
wrote a tiny program (attached) to check this issue. This program merely construct
an employee instance using a typical constructor which accept the object's initial
values.
The
code is shown below, but I wanted to talk about the results first:
The
times here are in minutes : seconds . milliseconds . Each point in the graph is
greater than the previous one by one hundred thousand objects. As you can see,
to create 5,000,000 objects it takes less the two and a half seconds.
So
I wouldn't particularly worry about instantiating objects (this doesn't
include objects that holds scarce resources , like database connections, of
course).
The
overall test create 127,500,000 objects and took less than 1 minutes and 9
seconds.
Here
is the code. It is ugly, but it does the job.
class
Program {
public class Employee
{
string name, lastName, email;
DateTime birthDay;
int age;
public Employee(string
name, string lastName, string email, DateTime
birthDay, int age)
{
this.name = name;
this.lastName = lastName;
this.email = email;
this.birthDay = birthDay;
this.age = age;
}
public string
Name
{
get { return
name; }
set { name = value;
}
}
public string
LastName
{
get { return
lastName; }
set { lastName = value;
}
}
public string
Email
{
get { return
email; }
set { email = value;
}
}
public DateTime
BirthDay
{
get { return
birthDay; }
set { birthDay = value;
}
}
public int
Age
{
get { return
age; }
set { age = value;
}
}
}
static void
Main(string[] args)
{
((Action<int>)
Foo).BeginInvoke(1, null,null);
Console.ReadKey();
}
private static
void Foo(int
ignored)
{
string[] names = { "Foo",
"Bar" };
string[] surnames = { "foo", "bar"
};
DateTime[] dates = { DateTime.MaxValue,
DateTime.MinValue };
string[] emails = { "E@f.com",
"Bar@asdd.com" };
int[] ages = { 1, 23 };
StreamWriter text = File.CreateText("log.txt");
for (int
multiply = 0; multiply < 1000; multiply++)
{
List<Employee>
emps = new List<Employee>();
DateTime start = DateTime.Now;
int max = 100000 * multiply;
for (int i =
0; i < max; i++)
{
Employee emp = new
Employee(names[i % 2],
surnames[i % 2],
emails[i % 2],
dates[i % 2],
ages[i % 2]);
emps.Add(emp);
if (i == 5000)
emps.Clear();
}
string format = string.Format("{0}\t{1}", max, DateTime.Now - start);
text.WriteLine(format);
Console.WriteLine(format);
}
Console.WriteLine("Done");
} } |
Comments
Comment preview