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都指向同一个整数数组一样?
数组通过引用传递,因此两个片段在效率上都是等效的,除了以下事实之外:如果您不将其 intArray
用于其他目的:第二个版本将取消引用该数组,并使其成为垃圾回收的候选对象。
这是在第二种情况下,数组将是someMethod
执行返回后立即要收集的候选对象,而第一种版本则将保持引用数组直到程序结束,因为它是静态的。
根据您的评论,我知道您将为className
每个文件调用一次不同的文件,并且对于每个文件,您将多次调用“ someMethod”。然后,我喜欢在某些方面与第一个类似但与第一个和第二个不同的解决方案。
该解决方案是为Testing
您从中加载数据的每个文件提供一个实例:
className
以便它将仅从其文件中加载数据一次。为Testing
及其实例指定合适的用户。
class Testing{
public Testing(File f)
{
this.f = f;
}
private File f;
private int[] intArray;
public static ReturnClassName className(){
ReturnClassName returnCN= new ReturnClassName();
byte[] b;
if(intArray == null || intArray.length > 0) return //If it was called before, then we don't load the file again.
{
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
} catch(Exception e) {
...
...
}
}
returnCN.setNumber(someMethod(5));
return returnCN;
}
private int[] someMethod(int l){
return Arrays.copyOfRange(intArray, counter, counter + 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();
另一方面,如果您有一个由输入文件(例如缓存)索引的整数数组的映射,并且保留了字节的副本,则可以实现更好的解决方案。因此具有单个实例odTesting
并保留File f
为“ className”的输入参数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句