昨天跟朋友争论了一下 这个关键词,因为在以前的项目中我经常会用到!
当时只简单地看了一下这个关键词的作用!
对象中被transient 修饰的变量表示一个特殊的数据成员变量,在该对象被序列化的时候,被transient 修饰的变量不包括在序列化中。
在以前的项目里,我为了使用组合模式,大量地在变量前加上transient 来修饰,表示这个是临时的,特殊的,不被序列化的,
其实根本没有考虑过所在的对象是否需要序列化!
在前面的项目里,网络传输一个对象的方式很多,还有保持一个对象到mysql数据库为blob类型的也比较多,
在这些对象里面使用transient 关键词来修饰不需要被序列化的变量是最为恰当的!
而在普通的对象,那些不需要被序列化的对象就没必要使用transient 关键词!
思考:如果在普通的对象,那些不需要被序列化的对象使用的话,只是用于区分说明,仅表示一个标识,这样会对性能造成影响么?
经过几次反复测试 发现还是会受影响的!
以上是测试代码
类A 用transient 修饰了成员变量c
package test;
public class A {
private int a;
private int b;
private transient int c;
public A(int a, int b, int c) {
super();
this.a = a;
this.b = b;
this.c = c;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
public int getC() {
return c;
}
@Override
public String toString() {
return "A [a=" + a + ", b=" + b + ", c="+c+"]";
}
}
类B
package test;
public class B {
private int a;
private int b;
private int c;
public B(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
public int getC() {
return c;
}
@Override
public String toString() {
return "B [a=" + a + ", b=" + b + ", c=" + c + "]";
}
}
package test;
public class Main {
public static void main(String[] args) {
long s1 = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
A a = new A(1, 2, 3);
if(i==0)
System.out.println(a);
}
System.err.println("A- "+(System.currentTimeMillis()-s1) + " ms");
long s2= System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
B b = new B(1, 2, 3);
if(i==0)
System.out.println(b);
}
System.err.println("B- "+(System.currentTimeMillis()-s2) + " ms");
}
}
经过测试后结果为:
A [a=1, b=2, c=3]
A- 16 ms
B [a=1, b=2, c=3]
B- 0 ms
同时在测试过程中小刚发现如果不重写A类 的toString()方法,把变量c赋值进去, A对象实例是不包含在tostring()方法的默认字符串中的。虽然A已在构造函数中赋值,但是调用tostring()方法得到的输入结果应该为: A [a=1, b=2] ;