Skip to Content
Java并发编程实战
book

Java并发编程实战

by Brian Goetz, Tim Peierls
August 2021
Beginner to intermediate
450 pages
5h 40m
Chinese
Pearson
Content preview from Java并发编程实战

12.3 避免性能测试的陷阱

理论上,开发性能测试程序是很容易的——找出一个典型的使用场景,编写一段程序多次执行这种使用场景,并统计程序的运行时间。但在实际情况中,你必须提防多种编码陷阱,它们会使性能测试变得毫无意义。

12.3.1 垃圾回收

垃圾回收的执行时序是无法预测的,因此在执行测试时,垃圾回收器可能在任何时刻运行。如果测试程序执行了N次迭代都没有触发垃圾回收操作,但在第N+l次迭代时触发了垃圾回收操作,那么即使运行次数相差不大,仍可能在最终测试的每次迭代时间上带来很大的(但却虚假的)影响。

有两种策略可以防止垃圾回收操作对测试结果产生偏差。第一种策略是,确保垃圾回收操作在测试运行的整个期间都不会执行(可以在调用JVM时指定-verbose:gc来判断是否执行了垃圾回收操作)。第二种策略是,确保垃圾回收操作在测试期间执行多次,这样测试程序就能充分反映出运行期间的内存分配与垃圾回收等开销。通常第二策略更好,它要求更长的测试时间,并且更有可能反映实际环境下的性能。

在大多数采用生产者-消费者设计的应用程序中,都会执行一定数量的内存分配与垃圾回收等操作——生产者分配新对象,然后被消费者使用并丢弃。如果将有界缓存测试运行足够长的时间,那么将引发多次垃圾回收,从而得到更精确的结果。

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

数据驱动力:企业数据分析实战

数据驱动力:企业数据分析实战

Carl Anderson
Python机器学习案例精解

Python机器学习案例精解

Posts & Telecom Press, Yuxi (Hayden) Liu
RxJava反应式编程

RxJava反应式编程

Tomasz Nurkiewicz, Ben Christensen
软件开发实践:项目驱动式的Java开发指南

软件开发实践:项目驱动式的Java开发指南

Raoul-Gabriel Urma, Richard Warburton

Publisher Resources

ISBN: 9787111370048