简体   繁体   English

变量,在类或方法中哪个更好?

[英]variables, in a class or in a method which is better?

just wondering which one of these would be the best to practice? 只是想知道哪一个是最好的练习?

code 1: 代码1:

public void push<T>(T pushthis)
{
    pusher pusher = new pusher();
    pusher.push(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(pushthis));
}

code 2: 代码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: 代码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. 我想知道是否更好地为序列化器创建一个变量,如果是的话放在哪里,在方法内部或类内部我将使用push方法多次,只使用类推送器的一个实例。

And if possible, can you site some references for me to study for code optimization 如果可能的话,你能为我提供一些参考资料来研究代码优化

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. 没有其他地方使用serializer器。

The third way of coding reuses serializer across multiple invocations of pusher . 第三种编码方式是在多个调用者调用中重用serializer pusher It does not call the constructor of JavaScriptSerializer multiple times, and therefore may be more efficient. 它不会多次调用JavaScriptSerializer的构造函数,因此可能更有效。

You could possibly share JavaScriptSerializer among all instances of class pusher by making the serializer variable static . 您可以通过使serializer变量为static在所有pusher实例中共享JavaScriptSerializer Unless you change configuration dynamically, for example by calling RegisterConverters , you may be able to reduce the number of invocations of the constructor further. 除非您动态更改配置,例如通过调用RegisterConverters ,否则您可以进一步减少构造函数的调用次数。

我不认为代码1和代码2有很大的不同。如果你多次使用push方法,那么使它成为类级变量而不是本地/方法级变量

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. 在方法中创建对象时,它将在方法结束时超出范围并有效地进行GC。

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. 如果您将JavaScriptSerializer声明为类的字段,则需要确保它是线程安全的,如果您将同时调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM