如何优化数据结构?
1、优先使用数组以及字符串,而不是集合类。也就是说,优先用array,而不是ArrayList、LinkedList、HashMap等集合。
比如,有个List list = new ArrayList(),将其替换为int[] arr = new int[]。这样的话,array既比List少了额外信息的存储开销,还能使用原始数据类型(int)来存储数据,比List中用Integer这种包装类型存储数据,要节省内存的多。
还比如,通常企业级应用中的做法是,对于HashMap、List这种数据,统一用String拼接成特殊格式的字符串,
比如Mappersons = new HashMap ()。可以优化为,特殊的字符串格式:id:name,address|id:name,address...。复制代码
2、避免使用多层嵌套的对象结构。比如说,
public class Teacher { private Liststudents = new ArrayList () }。复制代码
就是非常不好的例子。因为Teacher类的内部又嵌套了大量的小Student对象。 比如说,对于上述例子,也完全可以使用特殊的字符串来进行数据的存储。比如,用json字符串来存储数据,就是一个很好的选择。
{ "teacherId": 1, "teacherName": "leo", students:[{ "studentId": 1, "studentName": "tom"},{ "studentId":2, "studentName":"marry"}]}复制代码
例如mapreduce程序:context.write(new Text(key),new person());Person p1 = new Person(1,"zahngsan")String str = JSON.toJSON(p1)context.write(new text(key),str)复制代码
3、对于有些能够避免的场景,尽量使用int替代String。因为String虽然比ArrayList、HashMap等数据结构高效多了,占用内存量少多了,但是之前分析过,还是有额外信息的消耗。比如之前用String表示id,那么现在完全可以用数字类型的int,来进行替代。这里提醒,在spark应用中,id就不要用常用的uuid了,因为无法转成int,就用自增的int类型的id即可。(sdfsdfdf-234242342-sdfsfsfdfd)