Reputation: 229
just wondering which one of these would be the best to practice?
code 1:
public void push<T>(T pushthis)
{
pusher pusher = new pusher();
pusher.push(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(pushthis));
}
code 2:
public void push<T>(T pushthis)
{
pusher pusher = new pusher();
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
pusher.push(serializer.Serialize(pushthis));
}
code 3:
public class pusher()
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
public void push<T>(T pushthis)
{
pusher pusher = new pusher();
pusher.push(serializer.Serialize(pushthis));
}
}
I want to know if better make a variable for serializer, and if yes where to put it, inside the method or inside the class And i will be using the push method many times, with just an instance of the class pusher.
And if possible, can you site some references for me to study for code optimization
Upvotes: 1
Views: 132
Reputation: 14521
Best thing to do is to measure performance.
I really doubt you'll see much difference, if any. When you create an object in a method it will go out of scope at the end of the method and be efficiently GC'd.
If you declare the JavaScriptSerializer as a field on the class you need to make sure that it is thread-safe if you'll be calling it concurrently.
Upvotes: 1
Reputation: 726499
The first and the second ways of coding the method are identical. The local variable is defined and used immediately; there are no other places where serializer
is used.
The third way of coding reuses serializer
across multiple invocations of pusher
. It does not call the constructor of JavaScriptSerializer
multiple times, and therefore may be more efficient.
You could possibly share JavaScriptSerializer
among all instances of class pusher
by making the serializer
variable static
. Unless you change configuration dynamically, for example by calling RegisterConverters
, you may be able to reduce the number of invocations of the constructor further.
Upvotes: 2
Reputation: 11
I dont think there is much difference in code 1 and code 2. If you are using the push method multiple times then make it a class level variable rather than local /method level variable
Upvotes: 1