1. Does Java have an operator similar to sizeof () in C?
On the surface, the answer is that Java does not provide any sizeof () operator similar to the C language. However, we should think about why Java programmers occasionally need it.
C language programmers manage most data structure storage distributions by themselves, and sizeof () is not responsible for understanding the size of the allocated storage block. C Storage Allocator such as malloc (), as long as it involves object initialization, almost nothing is done: the programmer must set all object domains as a deeper object pointer. However, when all said and encoded, the C/C ++ storage allocation is quite effective.
In contrast, Java object allocation and construction work closely together (it is impossible to use an allocated but not initialized object ). If a Java class defines the fields referenced as a deeper object, it is also common to set them during the construction phase. As a result, Java object distributors frequently allocate interconnect objects: Object graphics. Coupled with automatic garbage collection, all this is too convenient, and you don't have to worry about the details of Java storage allocation.
Of course, this is only effective for simple Java applications. Compared with C/C ++, the same Java data structure often occupies more physical storage. In enterprise software development, the maximum virtual storage close to today's 32-bit JVM is a common scalability restriction. Therefore, Java programmers can benefit from sizeof () or other similar functions because these functions can observe whether their data structures are too large or contain storage bottlenecks. Fortunately, Java reflection allows you to easily write such a tool.
Next, I will first discuss several frequently encountered errors about the problem.
Misunderstanding 1: sizeof () is not required because the Java type size is determined ()
Yes, Java Int Is 32-bit on all JVM and all platforms, but it is only a standard requirement of the language. programmers can accept the width of this data type. This int type is basically an abstract data type and can be supported by the 64-Bit Memory words on a 64-bit device. Non-elementary types are no exception: Java language norms do not involve such issues at all: how to calibrate the class domain in physical storage or arrange the Boolean In the JVM cannot be implemented as a simple bit vector.
Misunderstanding 2: Serial objects into a single-bit flux and then view the generated flux length to measure the object size.
This method is ineffective because the serial layout is only a remote reflection of the layout in the real memory. For example, by observing how the string is serialized: Each char in the memory has at least two bytes, but in the serial format the string is UTF-8 encoded, therefore, only half of the ASCII content is occupied.
Another solution
You may think of "Java tip 130: Do you know your data size? "This article describes a technique: Carefully measuring the increase in the size of the stack used by JVM based on the creation of a large number of tag classes. If appropriate, this technique is quite useful. In fact, I also use it in this article to guide the alternative method.
Note:: The sizeof class in Java tip 130 requires a static JVM (in this way, the stack activity can only be caused by the allocation of Objects requested by the measurement thread and the garbage collection operation), and a large number of instances of the same object are required. If you want to measure the size of a single large object (which may be part of the debugging Trace Output), especially if you want to test what actually makes it so big, this method is invalid.
2. What is the object size?
The above discussion highlights a philosophical question: If you often process object graphics, what is the definition of object size? Does it mean the size of the object instance you are measuring or the entire data graph rooted in the object instance? The latter is used more in real life. As you can see, things are not always clearly divided, but you can refer to the following methods for starting a program:
· The sum of all non-static data domains of an object (including the domains defined in the superclass) is its size.
· Unlike C ++, class Methods and Their virtualization do not affect the object size.
· The class superinterface does not affect the object size (see the comment at the end of the list)
· The complete object size can be obtained as the closure of the entire object image rooted in the startup object.
Note: Implement any Java interface to only mark the suspicious class without adding any data to its definition. In fact, the JVM does not even verify whether the interface implementation provides all the methods requested by the interface: In the current specification, this is strictly the responsibility of the compiler.
To guide the entire process, I use the Java 130 sizeof class to measure the physical size for the primary data type. As it proves, for a general 32-bit JVM, a simple Java. lang. the object occupies 8 digits, and the basic data type is usually the minimum physical size that can meet the language requirements (except that Boolean occupies the entire byte ):
// java.lang.Object shell size in bytes:public static final int OBJECT_SHELL_SIZE = 8;public static final int OBJREF_SIZE = 4;public static final int LONG_FIELD_SIZE = 8;public static final int INT_FIELD_SIZE = 4;public static final int SHORT_FIELD_SIZE = 2;public static final int CHAR_FIELD_SIZE = 2;public static final int BYTE_FIELD_SIZE = 1;public static final int BOOLEAN_FIELD_SIZE = 1;public static final int DOUBLE_FIELD_SIZE = 8;public static final int FLOAT_FIELD_SIZE = 4;
|
(These constants are not always hard-coded, and they must be measured independently for a given JVM. It is important to realize this.) Of course, the sum of naive computing object domain sizes often ignores the storage queue issue in JVM. The storage queue is really relevant (for example, the primary arrangement type in Java tip 130), but I think it is useless to write a post on such low-level details. Such details are not only determined by JVM developers, but also under the control of programmers. Our goal is to get the best estimation of the object size, and we hope to get a tip when the class domain is redundant, the domain should be simply assembled, or when it is necessary to embed the database more compact. For absolute physical precision, you can always return to the sizeof class in Java tip 130.
To help make up the configuration file of the object instance, our tool not only calculates the size, but also creates an attached useful data structure: a graph composed of iobjectprofilenode:
interface IObjectProfileNode{ Object object (); String name (); int size (); int refcount (); IObjectProfileNode parent (); IObjectProfileNode [] children (); IObjectProfileNode shell (); IObjectProfileNode [] path (); IObjectProfileNode root (); int pathlength (); boolean traverse (INodeFilter filter, INodeVisitor visitor); String dump ();} // End of interface
|
Iobjectprofilenodes is connected in a very similar way to the original object graph. It uses the iobjectprofilenode. Object () function that returns the actual object represented by each node. Iobjectprofilenode. Size () returns the total size (in bytes) of the object subtree that takes the object instance of the node as the root ). If the object instance is linked to another object through a non-empty instance domain or a reference contained in the Arrangement domain, iobjectprofilenode. children () is a list of child graph nodes in descending order. Instead, for each node that is not the Start Node, iobjectprofilenode. Parent () Returns their parent node. Therefore, the entire collection of iobjectprofilenode will cut off the original object and show how the object is stored internally separated. In addition, the graphic node name is derived from the class domain and the Node path (iobjectprofilenode. Path () in the graph allows you to trace the ownership link from the original object instance to any part of the data.
You may have noticed that some of the above paragraphs are vague. How do you assign ownership (parent pointer) to an object that you encounter more than once during graph traversal )? Consider the following code snippets:
Object obj = new String [] {new String ("JavaWorld"), new String ("JavaWorld")};
|
Each java. Lang. String instance has an internal domain of the char type [], and the char type [] has real string content. The string replication constructor is valid in Java 2 Standard Edition (j2se) 1.4. The two string instances in the preceding arrangement share the same {'J', 'A ', 'V', 'A', 'w', 'O', 'R', 'l', and 'D'} character sequences are arranged in char. The two strings belong to the same arrangement. What should you do in this case?
If I always want to assign a single parent node to a graphic node, there is no general answer to this question. But in fact, many such object instances can be traced back to a single "natural" parent node. This natural link sequence is usually shorter than other shorter paths. Consider the data pointed to by the instance domain as belonging to the instance rather than others. Consider the items in the arrangement as belonging to the arrangement itself. Therefore, if the internal object instance can be reached through several channels, we select the shortest path. If the path is the same as long, We will select the one we first found. In the worst case, this omnipotent strategy is useful. Consider graph traversal and shortest path. Note this: The width-first search ensures that the shortest path between the Start Node and any other graphic nodes can be found.