FastJson 原理

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

1 序列化:通过asm 获取对象上的属性的get方法集合,然后通过调用相应的方法拼装出json字符串。


2 反序列化:通过asm 获取对象上的属性的set方法集合,然后调用set方法集合,赋值到相应的属性。

  所有的parser基本上都需要做词法处理,json也不例外。fastjson词法处理的时候,使用了基于预测的优化算法。比如key之后,最大的可能是冒号":",value之后,可能是有两个,逗号","或者右括号"}"。


3 封装了ASM,直接操作java类文件,获取要序列化和反序列化的类的属性方法,get set 等。


4 实现了一个类似StringBuffer的可以append的对字符串操作的类。实现了Appendable接口。

SerializeWriter功能和StringBuffer类似。里面增加了ThreadLocal变量来存储char[]buf 数组,减少对内存的分配与回收。

提供一些针对性的方法减少数组越界检查。


5 IdentityHashMap  个人感觉这个map实现仅仅是针对fastJson场景用来存储类(.class,加载时就分配规定的内存地址)。所以该类不适合做其他用处。

public class IdentityHashMap {

    public static final int     DEFAULT_TABLE_SIZE = 1024;

    private final Entry[] buckets;
    private final int           indexMask;

    public IdentityHashMap(){
        this(DEFAULT_TABLE_SIZE);
    }

    public IdentityHashMap(int tableSize){
        this.indexMask = tableSize - 1;
        this.buckets = new Entry[tableSize];
    }
    //要求必须用同一个内存分配的对象去取才可以,不然buckets定位不到,或者 == 判断通过重新分配的值相同的String    // 会有问题。
    public final V get(K key) {
        final int hash = System.identityHashCode(key);
        final int bucket = hash & indexMask;

        for (Entry entry = buckets[bucket]; entry != null; entry = entry.next) {
            if (key == entry.key) {
                return (V) entry.value;
            }
        }

        return null;
    }

    public boolean put(K key, V value) {
        final int hash = System.identityHashCode(key);
        final int bucket = hash & indexMask;

        for (Entry entry = buckets[bucket]; entry != null; entry = entry.next) {
            if (key == entry.key) {
                entry.value = value;
                return true;
            }
        }

        Entry entry = new Entry(key, value, hash, buckets[bucket]);
        buckets[bucket] = entry;  

        return false;
    }

    public int size() {
        int size = 0;
        for (int i = 0; i < buckets.length; ++i) {
            for (Entry entry = buckets[i]; entry != null; entry = entry.next) {
                size++;
            }
        }
        return size;
    }

    protected static final class Entry {

        public final int   hashCode;
        public final K     key;
        public V     value;

        public final Entry next;

        public Entry(K key, V value, int hash, Entry next){
            this.key = key;
            this.value = value;
            this.next = next;
            this.hashCode = hash;
        }
    }

}


转载于:https://my.oschina.net/robinyao/blog/477394

你可能感兴趣的:(FastJson 原理)