Java的性能:是否将一个hashMap值存储在一个变量冗余? [英] java performance : Is storing a hashMap value in a variable redundant?

查看:115
本文介绍了Java的性能:是否将一个hashMap值存储在一个变量冗余?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是减少内存使用量。
如果我需要多次使用该值,我应该将hashMap值存储在一个变量中?

  public void upcCheck (){
String prodUPC = pHashMap.get(productUpc);
if(prodUpc ==''){
// do stuff;
}
else if(prodUpc =='0123456'){
// do other stuff;






$ b我应该总是使用hashMap的get()方法来避免冗余和不必要的内存使用?

  public void upcCheck(){

if(pHashMap .get(productUpc)==''){
// do stuff;
}
else if(pHashMap.get(productUpc)=='0123456'){
//做其他的事情;






哈希映射包含很多值ae:产品类型,产品价格等......许多方法都设置为与这些值一起工作。所以我想知道最好的方法。
谢谢!

解决方案

这不是多余的,并且不需要太多额外的内存。额外的变量不占用太多内存;正如这篇帖子中提到的那样,没有标准金额(取决于虚拟机),但金额足够小在这种情况下,如果您使用的是 List ,那么这很重要,看看如何使用根据数组的大小,访问该列表的时间可能会随时增加。这种时间测量称为时间复杂度。虽然,因为您使用的是 Map ,所以不必担心。



我宁愿使用额外的变量,因为它本身更容易阅读。最好选择可读性。删除变量不会引起任何明显的性能提升,看它如何不占用太多内存,也不应该担心。


my goal is to reduce memory usage. should I store a hashMap value in a variable if I need to use that value multiple times?

public void upcCheck() {
          String prodUPC = pHashMap.get("productUpc");
          if(prodUpc == ''){
            //do stuff;
          }
          else if(prodUpc == '0123456'){
            //do other stuff;
          }
    }

Or should I just always use the hashMap's get() method to avoid redundancy and unecessary memory usage?

 public void upcCheck() {

              if(pHashMap.get("productUpc") == ''){
                //do stuff;
              }
              else if(pHashMap.get("productUpc") == '0123456'){
                //do other stuff;
              }
        }

The hashMap contains alot of values ae: product type, product price etc... Many methods are set to work with those values. So I was wondering about the best approach. Thank you!

解决方案

It's not redundant, and doesn't take a lot of extra memory. Extra variables don't take much memory; as this post mentions, there is no standard amount (it depends on the vm), but the amount is small enough to not worry about.

In a situation like this, if you were using a List, it would matter, seeing how accessing that list can increase in time depending on the size of the array. This measurement of time is called the time complexity. Although, since you're using a Map, it's not something to worry about.

I would prefer using the extra variable, since it's personally easier to read. It's always best to prefer readability. Removing the variable will not cause any noticable performance boosts, seeing how it doesn't take much memory at all, and shouldn't be something to worry about.

这篇关于Java的性能:是否将一个hashMap值存储在一个变量冗余?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆