如何判断Java代码的效率

发布于 2024-11-08 18:40:55 字数 238 浏览 0 评论 0原文

我刚刚意识到我不知道如何从计算的角度判断一段 Java 代码是否高效。读几个源代码有时我觉得我正在读的代码效率很低,有时我的感觉恰恰相反。

您能否列出需要遵守的基本one-line规则以及为什么它们如此重要?

编辑 - 我的问题与 JVM 的 Java 实现有关,例如 Java 分配问题、字符串管理、异常处理、线程同步等。

预先感谢

。请不要从字面上理解“一行”

I just realized that I have no idea on how to tell whether or not a piece of Java code is efficient from the computational point of view. Reading several source codes sometimes I feel that the code I'm reading is highly inefficient, some other times I feel the opposite.

Could you list the basic one-line rules to respect and why they are so important?

edit - My question is related to the Java implementations of the JVM, so things like Java allocation issues, String management, exception handling, thread synchronization and so on.

Thanks in advance

p.s. don't take the "one-line" literally pls

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

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

发布评论

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

评论(5

不寐倦长更 2024-11-15 18:40:55

基本的一行规则?好的,给你:

避免不必要的计算。

你怎么做?抱歉,没有一句话可以回答这个问题。 :(

嗯,人们在大学里花费数年时间学习计算机科学中的算法和数据结构是有原因的......可能想在某个时候学习算法/数据结构课程。


我不确定你所说的“从计算中”是什么意思观点”(似乎暗示算法问题),但假设您的意思是更类似于分析之类的技巧,请尝试以下操作:

  • 运行程序,然后突然暂停它,看看它在哪里暂停。这样做几次次;停得最多的地方是 ,

  • 避免装箱/拆箱(在intInteger之间转换等); >整数[], List 以及其他内部存储原始类型对象数组的内容

  • 分解公共代码(有时是速度问题,有时是可读性)

  • 避免使用 String 操作进行循环;使用 StringBuilder/StringBuffer 代替。 (简而言之,避免在不需要时创建和/或复制数据。)

如果想到其他事情,我会补充这一点。

Basic one-line rule? Okay, here you go:

Avoid unnecessary computations.

How do you do it? Sorry, no one-line answer to that. :(

Well, people spends years in college learning about algorithms and data structures in computer science for a reason... might want to take a course on algorithms/data structures sometime.


I'm not sure what you mean by "from a computation point of view" (it seems to imply algorithm issues), but assuming you mean tricks more similar to things like profiling, try these:

  • Run the program, then suddenly pause it, and see where it paused. Do this a few times; wherever it stops the most is a bottleneck, and how often it stops indicates how bad of a bottleneck it is.

  • Avoid boxing/unboxing (converting between int and Integer, etc.); especially avoid Integer[], List<Integer>, and other things that internally store arrays of objects of primitive types

  • Factor out common code (sometimes a speed issue, sometimes readability)

  • Avoid looping with String operations; use StringBuilder/StringBuffer instead. (In short, avoid creating and/or copying data when that's not needed.)

I'll add to this if other things come to mind.

戏舞 2024-11-15 18:40:55

使用分析。查看 JProfile 或任何其他分析器。

Use profiling. Look at JProfile or for any other profilers.

旧梦荧光笔 2024-11-15 18:40:55

我赞同梅尔达德的回答,因为绝对不存在“基本的一行规则”。

关于建议使用分析工具的答案,在您了解算法时间复杂度和大 O 表示法之前,分析并不是真正有用。来自维基百科关于 Big O 表示法的 文章

在数学、计算机科学和
相关领域,大O表示法
描述了限制行为
当参数趋向于函数时
朝向特定的价值或
无穷大,通常用更简单的形式表示
功能。大O表示法
根据以下特征描述函数
他们的增长率:不同
具有相同增长率的函数
可以使用相同的 O 来表示
符号。

大 O 表示法背后的想法是,它让您了解输入大小如何影响给定算法的执行时间。例如,考虑以下两种方法:

void linearFoo(List<String> strings){
    for(String s:strings){
      doSomethingWithString(s);
    }
}

void quadraticFoo(List<String> strings){
    for(String s:strings){
        for(String s1:strings){
            doSomethingWithTwoStrings(s,s1);
        }
    }
}

linearFoo据说是O(n),这意味着它的时间随着输入大小n线性增加(即strings.size())。 quadraticFoo 据说是 O(n2),这意味着执行 quadraticFoo 所需的时间是 字符串的函数。 size() 的平方。

一旦您了解了程序分析工具的算法时间复杂度,就会开始发挥作用。例如,您将能够知道,如果在分析时您发现某个方法对于固定输入大小通常需要 1 毫秒,如果该方法是 O(n),则将输入大小加倍将导致执行时间为 2 毫秒(1ms = n,因此 2n = 2ms)。但是,如果是 O(n2),则输入大小加倍意味着您的方法将需要大约 4ms 来执行(1ms = n2 因此 (2n)2 = 4ms)。

I'll second Mherdad's answer in that there definitely are no "basic one-line rules."

Regarding answers that suggest using profiling tools, profiling isn't really useful until you understand algorithmic time complexity and big-O notation. From wikipedia's article on Big O notation:

In mathematics, computer science, and
related fields, big-O notation
describes the limiting behavior of the
function when the argument tends
towards a particular value or
infinity, usually in terms of simpler
functions. Big O notation
characterizes functions according to
their growth rates: different
functions with the same growth rate
may be represented using the same O
notation.

The idea behind big-O notation is that it gives you a feel for how input size affects execution time for a given algorithm. For instance, consider the following two methods:

void linearFoo(List<String> strings){
    for(String s:strings){
      doSomethingWithString(s);
    }
}

void quadraticFoo(List<String> strings){
    for(String s:strings){
        for(String s1:strings){
            doSomethingWithTwoStrings(s,s1);
        }
    }
}

linearFoo is said to be O(n), meaning that its time increases linearly with the input size n (ie. strings.size()). quadraticFoo is said to be O(n2), meaning that the time it takes to execute quadraticFoo is a function of strings.size() squared.

Once you have a feel for the algorithmic time complexity of your program profiling tools will start to be useful. For instance, you'll be able to tell that if while profiling you find out that a method typically takes 1ms for a fixed input size, if that method is O(n), doubling the input size will result in an execution time of 2ms (1ms = n, therefore 2n = 2ms). However, if it is O(n2), doubling input size will mean that your method will take around 4ms to execute (1ms = n2 therefore (2n)2 = 4ms).

甜味拾荒者 2024-11-15 18:40:55

如果您确实需要以下列表,请查看 Joshua Bloch 所著的 Effective Java 一书在 Java 中应该遵循的规则。本书不仅提供了性能指南,而且还提供了 Java 编程的正确方法。

Take a look at the book Effective Java by Joshua Bloch if you really need a list of rules that you should follow in Java. The book offers guidelines not just for performance but also not he proper way of programming in Java.

无所谓啦 2024-11-15 18:40:55

您可以使用jconsole来监视应用程序的死锁、内存泄漏、线程和堆。简而言之,您可以在图表中看到应用程序的性能。

在此处输入图像描述

You can use jconsole for monitoring your application's deadlocks, memory leaks, threads and heap. In short you can see your applications performance in graphs.

enter image description here

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