初始化Gson对象的最佳方法

ua7*_*741 5 java performance android gson

出于以下两个选项,您更喜欢哪一个初始化Gson对象?有人可以帮我理解这两种方式对Android应用程序性能的影响(启动时间?),如果有的话.

// inline creation
private final Gson gson = new Gson();
Run Code Online (Sandbox Code Playgroud)

VS

// need base creation, overhead of sync everytime while accessing gson object
private synchronized Gson getOrCreateGson() {
    gson == null ? gson = new Gson() : gson;
    return gson.fromJson(jsonString, clazz);
}
Run Code Online (Sandbox Code Playgroud)

MrE*_*r13 7

这取决于你,但是private static final要照顾这个并没有错.您可以在此相关问题上阅读更多相关信息.

private static final Gson gson = new Gson();
Run Code Online (Sandbox Code Playgroud)