为什么积分慢

发布于 2024-09-18 11:11:18 字数 742 浏览 2 评论 0原文

我需要传递一个 x/y。我只是使用 java.awt.Point。考虑到这是应用程序的性质,我经常这样做,但比普通数组慢很多。我还尝试创建自己的“FastPoint”,它只是一个 int x/y 和非常简单的类构造函数,这也非常慢。

时间以毫秒为单位。

java.awt.点:10374
快点:10032
数组:1210

public class FastPoint {  

    public int x;  
    public int y;  

    public FastPoint(int x, int y) {  
            this.x = x;  
            this.y = y;  
    }
}

Jvisualvm 表示与简单的 int[] 数组相比,Point(无论是 awt 还是我自己的)正在使用大量内存。

我想这只是必须创建一个对象而不是一个基本类型的开销?有什么方法可以调整或优化这个 Point 类吗?我已经切换到基本的 int 数组(现在速度快得多),但只是想了解为什么它很慢以及我是否可以做些什么?

测试代码:

for (int i = 0; i < maxRuns; i++) { 
    point = new Point(i,i); 
}

for (int i = 0; i < maxRuns; i++) { 
    a[0] = i; a[1] = i; 
}

I need to pass an x/y around. I was just using java.awt.Point. I do this a lot considering it's the nature of the app, but tons slower then normal arrays. I also tried to create my own "FastPoint" which is just an int x/y and very simple class constructor, that's really slow too.

Time is in millescond.

java.awt.Point: 10374
FastPoint: 10032
Arrays: 1210

public class FastPoint {  

    public int x;  
    public int y;  

    public FastPoint(int x, int y) {  
            this.x = x;  
            this.y = y;  
    }
}

Jvisualvm says Point (either awt or my own) are using tons of memory compared to simple int[] array.

I guess that's just overhead from having to create an object instead of a um, basic type? Any way to tweak or optimize this Point class? I've already switched to basic int arrays (which is tons faster now), but just trying to understand why this is slow and if there is anything I can do about it?

Test Code:

for (int i = 0; i < maxRuns; i++) { 
    point = new Point(i,i); 
}

for (int i = 0; i < maxRuns; i++) { 
    a[0] = i; a[1] = i; 
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

百思不得你姐 2024-09-25 11:11:18

您的测试工具存在偏差:您在每次迭代中创建一个新点,但仅创建一次数组。如果将数组分配移到循环中,则差异没有那么大,数组实际上稍微慢一些:

Point:19 纳秒/迭代

数组:47 纳秒/迭代

这是预期的,因为数组访问需要执行边界检查,但字段赋值没有(JIT 显然已经内联了点构造函数)。

另请注意,为虚拟机进行 CPU 分析会产生额外的开销,在某些情况下,这可能会极大地改变被测应用程序的性能行为。

Your test harness is biased: You create a new point in each iteration, but create the array just once. If you move the array allocation into the loop, the difference is not as big, and arrays are actually slightly slower:

Point: 19 nano seconds / iteration

Array: 47 nano seconds / iteration

This is as expected, since array accesses need to perform bounds checking, but field assignment doesn't (the JIT has apparently inlined the point constructor).

Also note that instrumenting a virtual machine for cpu profiling incurs additional overhead, which can - in some cases drastically - change the performance behaviour of the application under test.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文