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?
class Program { 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?
Aucun commentaire:
Enregistrer un commentaire