Lua编译器是否优化了本地变量?

前端之家收集整理的这篇文章主要介绍了Lua编译器是否优化了本地变量?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_502_3@
当前的Lua编译器是否足够智能以优化用于清晰的局部变量?

  1. local top = x - y
  2. local bottom = x + y
  3. someCall(top,bottom)

或者手动内联的速度更快?

  1. someCall(x - y,x + y)

解决方法

由于Lua经常将源代码编译成字节代码,因此它被设计为快速单通道编译器.它确实做了一些常量折叠,但除此之外没有很多优化.您通常可以通过执行luac -l -l -p file.lua并查看生成的(反汇编的)字节代码来检查编译器的功能.

在你的情况下Lua代码

  1. function a( x,y )
  2. local top = x - y
  3. local bottom = x + y
  4. someCall(top,bottom)
  5. end
  6.  
  7. function b( x,y )
  8. someCall(x - y,x + y)
  9. end

结果通过luac5.3 -l -l -p file.lua运行后面的字节代码列表(跳过一些不相关的部分):

  1. function <file.lua:1,5> (7 instructions at 0xcd7d30)
  2. 2 params,7 slots,1 upvalue,4 locals,1 constant,0 functions
  3. 1 [2] SUB 2 0 1
  4. 2 [3] ADD 3 0 1
  5. 3 [4] GETTABUP 4 0 -1 ; _ENV "someCall"
  6. 4 [4] MOVE 5 2
  7. 5 [4] MOVE 6 3
  8. 6 [4] CALL 4 3 1
  9. 7 [5] RETURN 0 1
  10. constants (1) for 0xcd7d30:
  11. 1 "someCall"
  12. locals (4) for 0xcd7d30:
  13. 0 x 1 8
  14. 1 y 1 8
  15. 2 top 2 8
  16. 3 bottom 3 8
  17. upvalues (1) for 0xcd7d30:
  18. 0 _ENV 0 0
  19.  
  20. function <file.lua:7,9> (5 instructions at 0xcd7f10)
  21. 2 params,5 slots,2 locals,0 functions
  22. 1 [8] GETTABUP 2 0 -1 ; _ENV "someCall"
  23. 2 [8] SUB 3 0 1
  24. 3 [8] ADD 4 0 1
  25. 4 [8] CALL 2 3 1
  26. 5 [9] RETURN 0 1
  27. constants (1) for 0xcd7f10:
  28. 1 "someCall"
  29. locals (2) for 0xcd7f10:
  30. 0 x 1 6
  31. 1 y 1 6
  32. upvalues (1) for 0xcd7f10:
  33. 0 _ENV 0 0

如您所见,第一个变体(一个函数)有两个额外的MOVE指令和另外两个本地变量.

如果您对操作码的详细信息感兴趣,可以在lopcodes.h中查看OpCode枚举的注释.
例如. OP_ADD的操作码格式为:

  1. OP_ADD,/* A B C R(A) := RK(B) + RK(C) */

所以上面的2 [3] ADD 3 0 1从寄存器0和1(本例中的本地x和y)中取值,将它们加在一起,并将结果存储在寄存器3中.这是第二个操作码功能和相应的源代码在第3行.

@H_502_3@

猜你在找的Lua相关文章