Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

36
LINES

< > BotCompany Repo | #1011517 // unsafe_sizeOf

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (3986L/23K).

1  
static Map<Class, Int> unsafe_sizeOf_cache = weakHashMap();
2  
3  
static long unsafe_sizeOf(O o) {
4  
  if (isArray(o))
5  
    if (o cast O[])
6  
      ret inMemorySizeOfObjectArray(o.length);
7  
    else
8  
      ret inMemorySizeOfPrimitiveArray(o);
9  
      
10  
  Class c = _getClass(o);
11  
  Int l = unsafe_sizeOf_cache.get(c);
12  
  if (l == null)
13  
    unsafe_sizeOf_cache.put(c, l = unsafe_sizeOf_uncached(c));
14  
  ret l;
15  
}
16  
  
17  
static int unsafe_sizeOf_uncached(Class src) {
18  
  int WORD = javaDataModelWordSize();
19  
  int MIN_SIZE = 16;
20  
21  
  new L<Field> instanceFields;
22  
  while (src != null && src != O.class && empty(instanceFields)) {
23  
    for (Field f : src.getDeclaredFields())
24  
      if ((f.getModifiers() & Modifier.STATIC) == 0)
25  
        instanceFields.add(f);
26  
    src = src.getSuperclass();
27  
  }
28  
  
29  
  long maxOffset = MIN_SIZE-1;
30  
  
31  
  for (Field f : instanceFields) {
32  
     long offset = unsafe_objectFieldOffset(f);
33  
     if (offset > maxOffset) maxOffset = offset; 
34  
  }
35  
  ret (((int) maxOffset/WORD) + 1)*WORD;
36  
}

Author comment

from https://stackoverflow.com/questions/9368764/calculate-size-of-object-in-java (modified)

download  show line numbers  debug dex  old transpilations   

Travelled to 15 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt, xrpafgyirdlv

No comments. add comment

Snippet ID: #1011517
Snippet name: unsafe_sizeOf
Eternal ID of this version: #1011517/25
Text MD5: 95a47a60d60768231a5810dca1dfb384
Transpilation MD5: 27fef58c29c18859b4d29b4626fb271f
Author: stefan
Category: javax / unsafe
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-09-29 21:14:09
Source code size: 1015 bytes / 36 lines
Pitched / IR pitched: No / No
Views / Downloads: 890 / 1070
Version history: 24 change(s)
Referenced in: [show references]