Posted to tcl by cgm at Fri Dec 05 17:54:50 GMT 2025view raw

  1. Arjen asked:
  2. cgm, question about your [=] command. Since braces are not needed, what happens if you would have a code fragment like:
  3.  
  4. set sum 0
  5. foreach e $list {
  6. set sum [= sum [string length $e]]
  7. }
  8.  
  9. This gets compiled time and again, as the actual expression would change, wouldn't it, unlike the [expr] equivalent with braces?
  10. =================================================================
  11. Answer - See the four test procs below:
  12.  
  13. proc arjen_eq_comp {} {
  14. set list [lseq 10000]
  15. set sum 0
  16. foreach e $list {
  17. set sum [= sum + [string length $e]]
  18. }
  19. return $sum
  20. }
  21.  
  22. proc arjen_eq_noncomp {} {
  23. set list [lseq 10000]
  24. set sum 0
  25. foreach e $list {
  26. set sum [= sum+[string length $e]]
  27. }
  28. return $sum
  29. }
  30.  
  31. proc arjen_expr {} {
  32. set list [lseq 10000]
  33. set sum 0
  34. foreach e $list {
  35. set sum [expr {$sum + [string length $e]}]
  36. }
  37. return $sum
  38. }
  39.  
  40. proc arjen_expr_unbraced {} {
  41. set list [lseq 10000]
  42. set sum 0
  43. foreach e $list {
  44. set sum [expr $sum + [string length $e]]
  45. }
  46. return $sum
  47. }
  48.  
  49. Timings:
  50.  
  51. % timerate arjen_eq_comp
  52. 1998.69 µs/# 500 # 500.33 #/sec 999.347 net-ms
  53. % timerate arjen_eq_noncomp
  54. 7791.25 µs/# 128 # 128.35 #/sec 997.280 net-ms
  55. % timerate arjen_expr
  56. 1625.94 µs/# 615 # 615.03 #/sec 999.951 net-ms
  57. % timerate arjen_expr_unbraced
  58. 10227.6 µs/# 97 # 97.775 #/sec 992.075 net-ms
  59.  
  60.  
  61. When the [string length $e] command is given as a separate argument to =,
  62. it does get compiled to code which is almost as fast as expr.
  63. When it is not separated from the rest of the expression this is not possible
  64. and = falls back to a slower implementation, but this is still faster than
  65. unbraced expr.

Add a comment

Please note that this site uses the meta tags nofollow,noindex for all pages that contain comments.
Items are closed for new comments after 1 week