使用HashMap存储大量数据会减慢我的Android应用程序的速度,还有其他选择吗



我为我的学校编写了一个Android应用程序,它生成了一个HashMap,将课程名称映射到该课程的可用部分的ArrayList(字符串)。该地图是使用JSoup生成的,用于连接到学校网站并获取所有当前课程信息,对其进行解析和格式化,并创建HashMap>()。

它有效。然而,在Android设备上生成HashMap实际上需要大约5分钟。我是一个编程新手,我想知道是否有其他更有效的方法来存储和处理如此大量的数据(HashMap映射到大约800个ArrayList,每个ArrayList又包含几个字符串)。理想情况下,每次运行应用程序时都会更新数据,所以我不确定写入内部存储是否有效。

有什么建议吗?

感谢

Edit:这是创建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看看发生了什么。

最新更新