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).

static Map<Class, Int> unsafe_sizeOf_cache = weakHashMap();

static long unsafe_sizeOf(O o) {
  if (isArray(o))
    if (o cast O[])
      ret inMemorySizeOfObjectArray(o.length);
    else
      ret inMemorySizeOfPrimitiveArray(o);
      
  Class c = _getClass(o);
  Int l = unsafe_sizeOf_cache.get(c);
  if (l == null)
    unsafe_sizeOf_cache.put(c, l = unsafe_sizeOf_uncached(c));
  ret l;
}
  
static int unsafe_sizeOf_uncached(Class src) {
  int WORD = javaDataModelWordSize();
  int MIN_SIZE = 16;

  new L<Field> instanceFields;
  while (src != null && src != O.class && empty(instanceFields)) {
    for (Field f : src.getDeclaredFields())
      if ((f.getModifiers() & Modifier.STATIC) == 0)
        instanceFields.add(f);
    src = src.getSuperclass();
  }
  
  long maxOffset = MIN_SIZE-1;
  
  for (Field f : instanceFields) {
     long offset = unsafe_objectFieldOffset(f);
     if (offset > maxOffset) maxOffset = offset; 
  }
  ret (((int) maxOffset/WORD) + 1)*WORD;
}

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: 888 / 1067
Version history: 24 change(s)
Referenced in: [show references]