Java (一):Why Use Primitive Types In Java ?
Not everything in java is an object !
Java has a dual-type system, include Primitive Types and Object Types. Primitive types are value-based, but object types are reference-based.
There are eight primitive types predefined in Java. For each primitive type there is a corresponding wrapper class that is an object type.
Why use primitive type ?
The most important factor to consider for using primitive types in Java are performance, software performance is usually measured in terms of space and time.
space. java can use primitive types to create automatic variables (local variable 局部变量) that are not references. The variables hold the value, and it’s place on the stack(栈) so its much more efficient.
Creating an object using new isn’t very efficient because new will place objects on the heap(堆). This approach would be very costly for small and simple variables.
a single double occupy 8 bytes , a single Double occupy 24 bytes.primitive types创建的局部变量所占的空间,方法执行完后自动被释放掉;object types所占的空间,需触发GC回收, 方才释放。
Runtime Performance
To compare the runtime performances for primitives and objects, we need an algorithm dominated by numerical calculations. For this article I have chosen matrix multiplication, and I compute the time required to multiply two 1000-by-1000 matrices. Read More...