我为我的学校编写了一个 Android 应用程序,它生成一个 HashMap,它将类(class)名称映射到该类(class)可用部分的 ArrayList(字符串)。该 map 是使用 JSoup 生成的,连接到学校网站并获取所有当前类(class)信息,对其进行解析和格式化,并创建 HashMap>()。
它有效。然而,在 Android 设备上生成 HashMap 实际上需要大约 5 分钟。我是编程方面的新手,我想知道是否有其他更有效的方法来存储和处理如此大量的数据(HashMap 映射到大约 800 个 ArrayList,而每个 ArrayList 又包含几个字符串)。理想情况下,每次应用程序运行时都会更新数据,因此我不确定写入内部存储是否有效。
有什么建议吗?
谢谢
编辑:这是创建 HashMap 的方法。这有点令人费解,但我从中提取数据的网站并不容易使用。
public HashMap<String, ArrayList<String>> generateCourseSectionMap()
{
ArrayList<String> store = new ArrayList<String>();
CourseLinks courses = new CourseLinks();
HashMap<String, String> courseLinks = courses.getCourseMap();
StringUtils util = new StringUtils();
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
String sectionFormat = "((\\d){5};(\\d)+;(.*?) \\((.*?)\\);(.*?);(\\d)+ \\/ (\\d)+;(.*?);(TBA|Mo|Tu|We|Th|Fr|Sa|Su)+( (\\d){1,2}:(\\d){2}(AM|PM) - (\\d){1,2}:(\\d){2}(AM|PM))*?;(.*?));";
Document doc;
try
{
for (Map.Entry<String, String> entry : courseLinks.entrySet())
{
doc = Jsoup.connect(entry.getValue()).get();
Elements links = doc.select("*+tr>*:not(tr[class~=SectionTopic.*]>*):not(tr[class~=SectionTitle.*]>*)");
if (!links.isEmpty())
links.remove(0);
String build = "";
for (Element e : links)
{
String s = util.trim(e.text());
if (!s.isEmpty())
build = build + s + ";";
}
String rebuilt = rebuild(build);
store = util.toArrayList(rebuilt.split("BREAK"));
for (String d : store)
{
Pattern p = Pattern.compile(sectionFormat, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = p.matcher(d);
String[] array = d.split(";");
String firstKey = d.substring(0, d.indexOf(";"));
ArrayList<String> sectionList = new ArrayList<String>();
while (m.find())
sectionList.add(array[0] + ";" + array[1] + ";" + m.group());
map.put(firstKey, sectionList);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
return map;
}
最佳答案
首先,这个:
Pattern p = Pattern.compile(sectionFormat, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
为 for
循环中的每次迭代编译模式是次优的。
先编译一次,后续使用编译好的模式。
另外,这个:
build = build + s + ";";
由于 build
是一个字符串,重复连接它会在每次迭代时在内存中创建新字符串。
考虑使用 StringBuilder的 append
方法。
话虽如此,这些问题并没有严重到会减慢您的流程的程度。
现在没有足够的信息让我快速注意到更明显的问题,但似乎根据找到的链接数量和下载的页面数量,大部分时间可能花在阅读上来自网络并解析 HTML 页面。
您可能想要使用诸如 http://developer.android.com/tools/debugging/debugging-tracing.html 之类的工具看看发生了什么。
关于java - 使用 HashMap 存储大量数据会降低我的 Android 应用程序的速度,还有其他选择吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21068006/