Usage of ArrayList instead of Map in OkHttp

huangapple go评论46阅读模式
英文:

Usage of ArrayList instead of Map in OkHttp

问题

以下是要翻译的内容:

我正在查看 okhttp3 中 Header 类的源代码;为了存储标头和相应的值,使用了一个 ArrayList;因此,对于第一个键 0,其值将在 1 处等等...

这是执行此操作的方法:

final List<String> namesAndValues = new ArrayList<>(20);

Builder addLenient(String name, String value) {
    namesAndValues.add(name);
    namesAndValues.add(value.trim());
    return this;
}

所以我只想知道为什么使用 ArrayList 而不是类似于 Map 的数据结构。

英文:

I was going through the source of the Header class in okhttp3; For storing headers and the corresponding values, an ArrayList is used; So for first key 0, it's value will be at 1 and so on...

This is the method that does this work:

final List<String> namesAndValues = new ArrayList<>(20);

Builder addLenient(String name, String value) {
      namesAndValues.add(name);
      namesAndValues.add(value.trim());
      return this;
    }

So I just want to know the reason behind using an ArrayList instead of a Map like data structure

答案1

得分: 4

Header通常以multimap Map<String,List<String>>的形式呈现。

在内部,他们似乎决定使用单个列表来实现相同的目的。最初甚至是一个数组。我会说这更多是开发偏好,因为这是内部代码,对观众而言是隐藏的。

可能的做法是为了节省一些内存,而不是使用multimap并减少垃圾 - 想象一下有10个标头,它将是一个包含10个列表加上其中的项的映射。(通常这些是在每个http请求上创建的)

Headers类还应该有一个方法toMultimap

英文:

Header usually are presented with multimap Map<String,List<String>>

It seems internally they have decided to use a single list which serves the same purpose. Initially was even an array. I would say it is more a develop preference, as this is internal code and it is hidden for the audience.

Possible could be to save some memory instead of using multimap and less garbage - imagine having 10 headers it will be a map with 10 lists + the items inside.(Usually these are created on every http request)

Headers class should have also a method toMultimap

huangapple
  • 本文由 发表于 2020年7月28日 15:43:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63129255.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定