从语法结构上看,静态类和非静态类的差别在于:
①静态类只能拥有静态成员。
②非静态类可以有静态成员,也可以有非静态成员。
从含义上看,静态类和非静态类的差别在于
①静态类强调这个类是一种“工具类”,减少了代码的复杂度。
②因为静态类不能创建实列,因此它在整个项目中,可以模仿为“全局类,公用类”,做到资源共享。
③非静态类(仅有非静态成员)是不占内存的,只有实例才占内存,同时会被GC回收;但静态类始终占用内存(放在静态存储区),只有当程序结束后才会释放资源,能提高运行效率。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 字符串不可变性
{
class Program
{
static void Main(string[] args)
{
string str = null;
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 100000; i++)
{
str += i;
}
sw.Stop();
Console.WriteLine(str);
Console.WriteLine("总耗时:{0}",sw.Elapsed);
Console.Read();
}
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 字符串不可变性
{
class Program
{
static void Main(string[] args)
{
//string str = null;
StringBuilder sb = new StringBuilder();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 100000; i++)
{
// str += i;
sb.Append(i);//sb没有=+操作,而是append方法
}
sw.Stop();
Console.WriteLine(sb);
Console.WriteLine("总耗时:{0}",sw.Elapsed);
Console.Read();
}
}
}
差距在100倍。