Reputation: 2501
I have a question regarding Prototype Pattern.
I read that Prototype Pattern is effective as it copies the object instead of creating a new one, which is considered as an expensive operation.
So based on this I tried a sample and I see varied results. Am I checking it in the right way Or have I missed anything?
static void Main(string[] args)
{
var sw = new Stopwatch();
sw.Start();
Employee e;
for (var i = 0; i < 100000; i++)
{
e = new Employee(5, "sandesh", 27, "Bengaluru");
e.Print();
}
sw.Stop();
Console.WriteLine("New : " + sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
e = new Employee(5, "sandesh", 27, "Bengaluru");
for (var i = 0; i < 100000; i++)
{
var en = e.Clone();
en.Print();
}
sw.Stop();
Console.WriteLine("Clone : " + sw.ElapsedMilliseconds);
Console.ReadLine();
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Place { get; set; }
public Employee(int id, string name, int age, string place)
{
Id = id;
Name = name;
Age = age;
Place = place;
}
public Employee Clone()
{
return (Employee)this.MemberwiseClone();
}
public void Print()
{
var sum = Id * Age;
var full = sum + Name + Place;
}
}
And the results are below: 1st Run:- New: 18 Clone: 26
2nd Run:- New:34 Clone:30
3rd Run:- New:20 Clone:33
Appreciate if you can help me out in understanding this pattern. Also what extra does it takes to Create a new object, which doesn't happens in cloning?
Upvotes: 0
Views: 367
Reputation: 2265
It appears that you are looking for a metric that can be used to measure creation of an object versus cloning an object. In your sample you are creating objects, via different mechanisms, and looking for a difference in a metric.
What the Prototype pattern intends to do is reduce the creation time of an object, not from the mechanics of the compiler and byte code, but rather by avoiding time consuming operations that would normally be executed.
For example, if your Employee
object required a database call to be instantiated properly, then the Prototype pattern could be utilized to avoid that call. You would still be creating objects and setting values, as your code demonstrated, but the logical initialization of your object, the real data, would be short circuited. This is where the time saving comes in.
Upvotes: 4