Code 1:
listModel.getStockList().forEach((contractName, v) -> {
if (listModel.getContractDetails().get(contractName).getAskPrice() >
listModel.getArchieveContractDetails().get(contractName).getHighPrice()
&& validatorUtils.checkOrderValidity1(Action.BRAC_ORDER_1, contractName)) {
method1(listModel.getContractDetails().get(contractName).getAskPrice());
method2(0, listModel.getContractDetails().get(contractName).getAskPrice());
syso(listModel.getContractDetails().get(contractName).getAskPrice());
}
});
Code 2:
listModel.getStockList().forEach((contractName, v) -> {
int askPrice = listModel.getContractDetails().get(contractName).getAskPrice();
if (askPrice > listModel.getArchieveContractDetails().get(contractName).getHighPrice()
&& validatorUtils.checkOrderValidity1(Action.BRAC_ORDER_1, contractName)) {
method1(askPrice);
method2(0, askPrice);
syso(askPrice);
}
});
In code 1, I am reading price
directly from getaskPrice()
; and in code 2, I used an askPrice
variable.
Which approach will give me better performance and why?
Well, storing the result of get
in a variable and then using the variable multiple times should definitely never be any worse, performance-wise, than repeating the get
multiple times. Whereas the Hashmap
implementation might, or might not , perform comparably well on multiple get
s of the same key.
But consider that you are in complete control of how you write your Java code, but you are not necessarily in control of how good the HashMap
implementation is where your Java code runs.
Seems better to err on the side of caution and take control over the things you have control over (ie, do write your Java code to save the result of get
to be reused multiple times), rather than hope for the best in things you have little or no control over (ie, don't expect you'll always be running on a JDK with a "good" HashMap
implementation).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.