简体   繁体   English

Multimap和gson性能

[英]Multimap and gson performance

I am using both Gson and Guava. 我正在使用Gson和Guava。 I have a class that I want to serialize that looks like something like this sscce 我有一个我想序列化的类,看起来像这样的sscce

import com.google.common.collect.Multimap;
public class FooManager {
  private Multimap<String, Foo> managedFoos;
  // other stuff
}

Gson doesn't know how to serialize that. Gson不知道如何序列化。 So I did this: 所以我这样做了:

public final class FoomapSerializer implements
                          JsonSerializer<Multimap<String, Foo>> {
  @SuppressWarnings("serial")
  private static final Type t =
          new TypeToken<Map<String, Collection<Foo>>>() {}.getType();

  @Override
  public JsonElement serialize(Multimap<String, Foo> arg0, Type arg1,
        JsonSerializationContext arg2) {
    return arg2.serialize(arg0.asMap(), t);
  }
}

However, I'm afraid calling .asMap() over and over again will be slow, even if the underlying Map rarely changes. 但是,我害怕.asMap()调用.asMap()会很慢,即使底层Map很少改变。 (The serializations of the Foo objects will change often, but the mapping itself does not after initialization). Foo对象的序列化将经常更改,但映射本身不会在初始化之后)。 Is there a better way? 有没有更好的办法?

Multimap.asMap returns a cached view of the Multimap in O(1) time. Multimap.asMap在O(1)时间内返回Multimap的缓存视图。 It is not an expensive operation. 这不是一项昂贵的操作。 (In point of fact, it's quite cheap, requiring at most one allocation.) (事实上​​,它非常便宜,最多需要一次分配。)

Here's an example of a generic serializer for multimaps using Guava's TypeToken . 这是使用Guava的TypeToken的多图的通用序列化器的TypeToken There are some variations on this you could do if you wanted, like creating instances of the serializer for each multimap type you need to serialize so you only have to resolve the return type of asMap() once for each. 如果您愿意,可以执行此操作的一些变体,例如为每个需要序列化的多图类型创建序列化程序的实例,因此您只需为每个类型解析一次asMap()的返回类型。

public enum MultimapSerializer implements JsonSerializer<Multimap<?, ?>> {
  INSTANCE;

  private static final Type asMapReturnType = getAsMapMethod()
      .getGenericReturnType();

  @Override
  public JsonElement serialize(Multimap<?, ?> multimap, Type multimapType,
      JsonSerializationContext context) {
    return context.serialize(multimap.asMap(), asMapType(multimapType));
  }

  private static Type asMapType(Type multimapType) {
    return TypeToken.of(multimapType).resolveType(asMapReturnType).getType();
  }

  private static Method getAsMapMethod() {
    try {
      return Multimap.class.getDeclaredMethod("asMap");
    } catch (NoSuchMethodException e) {
      throw new AssertionError(e);
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM