【Java语言】while与for执行效率对比

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

【Java语言】while与for执行效率对比

/blog/1005821

测试环境(虚拟机版本): sun jdk build 1.6.0_22-b04

测试程序

Java代码

1./**

2. * Copyright (c) 2011 Trusted Software and Mobile Computing(TSMC)

3. * All rights reserved.

4. * Author: Jarg Yee

5. * /

6. */

7. import java.util.*;

8./*

9. * 【Java语言】while,for执行效率对比

10. */

11.public class WhileFor

12.{

13. public static void main(String[] args)

14. {

15. System.out.println(whileTest());

16. System.out.println(forTest());

17.

18. }

19.

20. /** while测试 */

21. public static long whileTest()

22. {

23. int num = Integer.MAX_VALUE; // 迭代次数

24. long sum = 0; // 保存加法结果

25.

26. while((num--)>0)

27. {

28. sum = sum + num;

29. }

30.

31. return sum;

32. }

33.

34. /** for测试 */

35. public static long forTest()

36. {

37. int num=Integer.MAX_VALUE; // 迭代次数

38. long sum = 0; // 保存加法结果

39.

40. for(;(num--)>0;)

41. {

42. sum = sum + num;

43. }

44.

45. return sum;

46. }

47.}

class文件反编译指令

---------- Java反编译----------

Class文件反编译指令代码

piled from "WhileFor.java"

2.public class WhileFor extends ng.Object{

3.public WhileFor();

4. Code:

5. 0: aload_0

6. 1: invokespecial #1; //Method java/lang/Object."":()V

7. 4: return

8.

9. LineNumberTable:

10. line 11: 0

11.

12.

13.

14.public static void main(ng.String[]);

15. Code:

16. 0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;

17. 3: invokestatic #3; //Method whileTest:()J

18. 6: invokevirtual #4; //Method java/io/PrintStream.println:(J)V

19. 9: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;

20. 12: invokestatic #5; //Method forTest:()J

21. 15: invokevirtual #4; //Method java/io/PrintStream.println:(J)V

22. 18: return

23.

24. LineNumberTable:

25. line 15: 0

26. line 16: 9

27. line 18: 18

28.

29.

30.

31.public static long whileTest();

32. Code:

33. 0: ldc #6; //int 2147483647

34. 2: istore_0

35. 3: lconst_0

36. 4: lstore_1

37. 5: iload_0

38. 6: iinc 0, -1

39. 9: ifle 20

40. 12: lload_1

41. 13: iload_0

42. 14: i2l

43. 15: ladd

44. 16: lstore_1

45. 17: goto 5

46. 20: lload_1

47. 21: lreturn

48.

49. LineNumberTable:

50. line 23: 0

51. line 24: 3

52. line 26: 5

53. line 28: 12

54. line 31: 20

55.

56.

57.

58.public static long forTest();

59. Code:

60. 0: ldc #6; //int 2147483647

61. 2: istore_0

62. 3: lconst_0

63. 4: lstore_1

64. 5: iload_0

65. 6: iinc 0, -1

66. 9: ifle 20

相关文档
最新文档