【发布时间】:2011-09-21 16:01:28
【问题描述】:
当 Array 的索引已知时,使用 Arrays 或 HashMaps 是否更好(在性能方面)?请记住,示例中的“对象数组/映射”只是一个示例,在我的实际项目中它是由另一个类生成的,所以我不能使用单个变量。
数组示例:
SomeObject[] objects = new SomeObject[2];
objects[0] = new SomeObject("Obj1");
objects[1] = new SomeObject("Obj2");
void doSomethingToObject(String Identifier){
SomeObject object;
if(Identifier.equals("Obj1")){
object=objects[0];
}else if(){
object=objects[1];
}
//do stuff
}
HashMap 示例:
HashMap objects = HashMap();
objects.put("Obj1",new SomeObject());
objects.put("Obj2",new SomeObject());
void doSomethingToObject(String Identifier){
SomeObject object = (SomeObject) objects.get(Identifier);
//do stuff
}
HashMap 看起来好多了,但我确实需要在这方面表现出色,以便优先考虑。
编辑:那么阵列就是这样,仍然欢迎提出建议
编辑:我忘了说,Array/HashMap 的大小总是一样的 (6)
编辑: HashMap 似乎更快 数组:128ms 哈希:103ms
当使用更少的周期时,HashMaps 的速度甚至是原来的两倍
测试代码:
import java.util.HashMap;
import java.util.Random;
public class Optimizationsest {
private static Random r = new Random();
private static HashMap<String,SomeObject> hm = new HashMap<String,SomeObject>();
private static SomeObject[] o = new SomeObject[6];
private static String[] Indentifiers = {"Obj1","Obj2","Obj3","Obj4","Obj5","Obj6"};
private static int t = 1000000;
public static void main(String[] args){
CreateHash();
CreateArray();
long loopTime = ProcessArray();
long hashTime = ProcessHash();
System.out.println("Array: " + loopTime + "ms");
System.out.println("Hash: " + hashTime + "ms");
}
public static void CreateHash(){
for(int i=0; i <= 5; i++){
hm.put("Obj"+(i+1), new SomeObject());
}
}
public static void CreateArray(){
for(int i=0; i <= 5; i++){
o[i]=new SomeObject();
}
}
public static long ProcessArray(){
StopWatch sw = new StopWatch();
sw.start();
for(int i = 1;i<=t;i++){
checkArray(Indentifiers[r.nextInt(6)]);
}
sw.stop();
return sw.getElapsedTime();
}
private static void checkArray(String Identifier) {
SomeObject object;
if(Identifier.equals("Obj1")){
object=o[0];
}else if(Identifier.equals("Obj2")){
object=o[1];
}else if(Identifier.equals("Obj3")){
object=o[2];
}else if(Identifier.equals("Obj4")){
object=o[3];
}else if(Identifier.equals("Obj5")){
object=o[4];
}else if(Identifier.equals("Obj6")){
object=o[5];
}else{
object = new SomeObject();
}
object.kill();
}
public static long ProcessHash(){
StopWatch sw = new StopWatch();
sw.start();
for(int i = 1;i<=t;i++){
checkHash(Indentifiers[r.nextInt(6)]);
}
sw.stop();
return sw.getElapsedTime();
}
private static void checkHash(String Identifier) {
SomeObject object = (SomeObject) hm.get(Identifier);
object.kill();
}
}
【问题讨论】:
-
等待;如果您“真的需要性能”,那么您已经知道这个问题的答案,因为您会分析您的应用程序以确定这个 Hashmap 与 Array 问题实际上是相关的。如果您没有这样做,您需要这样做以确定这确实会影响您的表现并且实际上并没有浪费时间。
-
好点子,但是作为一个新手程序员,如果你错过了什么或得到更好策略的建议,得到一些思考总是很好的
-
doSomethingToObject 多久调用一次?是的,新手程序员应该认真对待的建议是 Dour High Arch 的建议。
-
如果你“真的需要性能”你不应该用java写...
-
Dasdasd,您必须使用真实数据对运行的实际应用程序进行基准测试。用两个样本点编造虚假的“基准”只会误导你。您必须对整个应用程序进行基准测试并优化瓶颈,而不是选择看起来更改起来很有趣的代码行。如果这个问题不是瓶颈,那么无论你做多快,优化它都不会提高性能。
标签: java arrays performance optimization hashmap