原始数据类型的性能VS他们的Wrapper类

问题描述 投票:1回答:1

我试图测量原始数据类型的执行时间及其包装类来计算相同的数字。我得到的包装类比原始数据类型花费更多时间。

在我的下面的代码中,原始t1 = 5的执行时间和包装类t2的执行时间= 31。

import java.io.*;
import java.util.*;
public class Performance
{
  public static long primitive(int count)
     {
   long startTime = System.currentTimeMillis();
   for(int i=0;i<10000;i++)
     count++;
    System.out.println(count);
   long stopTime = System.currentTimeMillis();
   long elapsedTime = stopTime - startTime;
   return elapsedTime;
}
  public static long wrapper(Integer count)
{
    long startTime = System.currentTimeMillis();
    for(int i=0;i<10000;i++)
      count++;
      System.out.println(count);
    long stopTime = System.currentTimeMillis();
    long elapsedTime = stopTime - startTime;
    return elapsedTime;
 }

  public static void main(String args[])
  {

   Integer c = new Integer(0);
   long t2=Performance.wrapper(c);
    int count=0;
   long t1=Performance.primitive(count);
  System.out.println("t1="+t1+"t2="+t2);

  }
}

由于Wrapper类(Integer)或其他任何东西的对象创建,是否存在性能差异?

java performance execution boxing autoboxing
1个回答
10
投票

你在这里得到了必不可少的东西。

首先,编写一个好的微基准测试远远超出了你在代码中所做的工作;请参阅here了解一些指导原则。

然后:你必须了解你想要基准的东西。对不起,你显然没有。像这儿:

public static long wrapper(Integer count)
{
  long startTime = System.currentTimeMillis();
  for(int i=0;i<10000;i++)
    count++

整数对象是不可变的。此代码不仅“添加”Integer对象,还会在每次迭代时创建一个新的Integer对象。

当然:您的代码甚至不使用计算结果。如果JVM / JIT注意到它,它可能会完全抛弃循环并添加构造。所以你的方法应该至少返回count的最终值;并且调用者应该打印该结果。

并回答您的具体问题:当然使用引用类型包装类需要付出一定的代价。当你的程序正在处理(实际上)要处理的大量元素时,那么使用List of Integer确实比使用int数组要高得多。当你不注意并且你在你的代码中进行隐式自动装箱/拆箱时,那真的是hurt

但真正的答案是:你专注于错误的事情。你看,你的首要任务应该是做一个伟大的设计,然后是经过充分测试,健壮,可读,可维护的实现。当然,你不应该做完全愚蠢的事情并浪费性能,但是,在你担心性能之前,你最好还是担心你的Java技能。

长话短说:专注于理解java和“我如何创造一个好的设计”;暂时忘掉“表演”。只有在您的应用程序中出现真正的问题时,您才需要处理“性能”。然后你进行真正的分析,以确定根本原因并解决这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.