class Testing{
private static int counter;
private static int[] intArray;
public static ReturnClassName className(File f){
ReturnClassName returnCN= new ReturnClassName();
byte[] b;
try{
DataInputStream dataIStream= new DataInputStream(new FileInputStream(f));
intArray= new int[dataIStream.available()];
b= new byte[dataIStream.available()];
dataIStream.read(b);
intArray= b;
// setting methods for ReturnClassName
// counter increment
returnCN.setNumber(someMethod(5));
}//catch() block
return returnCN;
}
private static int[] someMethod(int l){
return Arrays.copyOfRange(intArray, counter, counter + l);
}或
class Testing{
private static int counter;
public static ReturnClassName className(File f){
ReturnClassName returnCN= new ReturnClassName();
byte[] b;
try{
DataInputStream dataIStream= new DataInputStream(new FileInputStream(f));
intArray= new int[dataIStream.available()];
b= new byte[dataIStream.available()];
dataIStream.read(b);
intArray= b;
// setting methods for ReturnClassName
// counter increment
returnCN.setNumber(someMethod(intArray,5));
}//catch() block
return returnCN;
}
private static int[] someMethod(int[] iArray, int l){
return Arrays.copyOfRange(iArray, counter, counter + l);
}我想知道哪一个是更优化和安全的上述两个代码。同样,在第二个代码中传递数组时,它是传递整个数组还是只传递该数组的地址。就像intArray和iArray都指向同一个整数数组一样?
发布于 2014-04-16 08:28:22
数组是通过引用传递的,因此这两个片段在效率方面是等价的,除非您的没有将 intArray用于其他目的:第二个版本将取消引用该数组并使其成为垃圾收集的候选对象。
在第二种情况下,当someMethod执行返回时,数组将是要收集的候选数组,而第一个版本将保持引用数组,直到程序结束,因为它是静态的。
从您的评论中我了解到,对于不同的文件,每个文件将调用一次className,而对于每个文件,您将多次调用“someMethod”。然后,我喜欢一个类似于firstone的解决方案,但与第一个和第二个不同。
该解决方案是为从以下位置加载数据的每个文件都提供一个Testing实例:
className,使其只从其文件中加载数据一次。Testing及其实例具有正确的用户。
类测试{公共测试(文件f) { the .f= f;}私有文件f;私有int[] intArray;公共静态ReturnClassName className(){ ReturnClassName returnCN=新ReturnClassName();byte[] b;如果(intArray == null \x/ intArray.length > 0)返回//如果以前调用了它,则不会再次加载该文件。{尝试{ DataInputStream dataIStream=新DataInputStream(新FileInputStream(f));intArray=新intdataIStream.available();b=新bytedataIStream.available();dataIStream.read(b);intArray= b;//设置ReturnClassName //计数器增量}catch(异常e) {.} returnCN.setNumber(someMethod(5));返回returnCN;}私有int[] someMethod(int l){返回Arrays.copyOfRange(intArray,计数器,计数器+ l);}}使用实例:
Testing forFile1 = new Testing(fileObj01);
ReturnClassName x = ReforFile1.className();
ReturnClassName y = ReforFile1.className();
Testing forFile2 = new Testing(fileObj02);
ReturnClassName z = ReforFile2.className();
ReturnClassName w = ReforFile2.className();另一方面,您可以实现一个更好的解决方案,如果您有一个由输入文件索引的整数数组映射(就像一个缓存),并且如果它们的字节在其中,那么您可以保留一个副本。具有一个Testing实例,并将File f作为'className‘的输入参数。
https://stackoverflow.com/questions/23103812
复制相似问题