当前位置:网站首页>Why does invariant mode improve performance

Why does invariant mode improve performance

2022-07-04 21:20:00 Daxing God

stay Java The wrapper classes of the basic types in are immutable classes , Such as Boolean、Byte、Character、Double、Float、Integer、Long、Short, And then there is String.
The instances created by these classes are immutable instances .

//Integer Class code  JDK1.8
public final class Integer extends Number implements Comparable<Integer> {
	private final int value;
	public Integer(int value) {
		this.value = value;
	}
}

You can see Integer Class is final Types cannot be inherited , Encapsulated int Value is also final Of . This leads to no other way to modify this after the instance is created int value , So Integer Objects are immutable objects .

How can immutable objects improve performance , Look here Integer Of valueOf Method .

    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

Integer Calling valueOf Time is first IntegerCache Look for objects , If not, just create a new object , If so, point the reference directly to this object .IntegerCache Is a static inner class , Store -128 To 127 An array of objects with values of .
because Integer Object is immutable , In this way, the cache array can be shared among multiple threads , Reduce Integer Object creation .
For example, you pass a ORM The frame finds 1 10000 personnel data , Personnel data usage Person Class encapsulation ,Person Class has a field Integer sex Store gender data ,1 male 2 Woman . Instantiate this 1 m Person Class, you can put this 1 m Integer sex Point to respectively Integer(1) and Integer(2) Memory address of . If Zhang San's current gender is male , You want to change to female , Then put sex The reference of points to the cache Integer(2) Memory address of . In this way, no extra Integer In the case of example , Achieve the purpose of saving memory .
In turn to see , If the object is mutable , There is no way to cache . Inside object int Value changes will make all references to this object unsafe , For each Person Create a Integer sex object .

原网站

版权声明
本文为[Daxing God]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207042016005148.html