reactiveObject.bench.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import { bench } from 'vitest'
  2. import { type ComputedRef, computed, reactive } from '../src'
  3. bench('create reactive obj', () => {
  4. reactive({ a: 1 })
  5. })
  6. {
  7. let i = 0
  8. const r = reactive({ a: 1 })
  9. bench('write reactive obj property', () => {
  10. r.a = i++
  11. })
  12. }
  13. {
  14. const r = reactive({ a: 1 })
  15. computed(() => {
  16. return r.a * 2
  17. })
  18. let i = 0
  19. bench("write reactive obj, don't read computed (never invoked)", () => {
  20. r.a = i++
  21. })
  22. }
  23. {
  24. const r = reactive({ a: 1 })
  25. const c = computed(() => {
  26. return r.a * 2
  27. })
  28. c.value
  29. let i = 0
  30. bench("write reactive obj, don't read computed (invoked)", () => {
  31. r.a = i++
  32. })
  33. }
  34. {
  35. const r = reactive({ a: 1 })
  36. const c = computed(() => {
  37. return r.a * 2
  38. })
  39. let i = 0
  40. bench('write reactive obj, read computed', () => {
  41. r.a = i++
  42. c.value
  43. })
  44. }
  45. {
  46. const r = reactive({ a: 1 })
  47. const computeds = []
  48. for (let i = 0, n = 1000; i < n; i++) {
  49. const c = computed(() => {
  50. return r.a * 2
  51. })
  52. computeds.push(c)
  53. }
  54. let i = 0
  55. bench("write reactive obj, don't read 1000 computeds (never invoked)", () => {
  56. r.a = i++
  57. })
  58. }
  59. {
  60. const r = reactive({ a: 1 })
  61. const computeds = []
  62. for (let i = 0, n = 1000; i < n; i++) {
  63. const c = computed(() => {
  64. return r.a * 2
  65. })
  66. c.value
  67. computeds.push(c)
  68. }
  69. let i = 0
  70. bench("write reactive obj, don't read 1000 computeds (invoked)", () => {
  71. r.a = i++
  72. })
  73. }
  74. {
  75. const r = reactive({ a: 1 })
  76. const computeds: ComputedRef<number>[] = []
  77. for (let i = 0, n = 1000; i < n; i++) {
  78. const c = computed(() => {
  79. return r.a * 2
  80. })
  81. computeds.push(c)
  82. }
  83. let i = 0
  84. bench('write reactive obj, read 1000 computeds', () => {
  85. r.a = i++
  86. computeds.forEach(c => c.value)
  87. })
  88. }
  89. {
  90. const reactives: Record<string, number>[] = []
  91. for (let i = 0, n = 1000; i < n; i++) {
  92. reactives.push(reactive({ a: i }))
  93. }
  94. const c = computed(() => {
  95. let total = 0
  96. reactives.forEach(r => (total += r.a))
  97. return total
  98. })
  99. let i = 0
  100. const n = reactives.length
  101. bench('1000 reactive objs, 1 computed', () => {
  102. reactives[i++ % n].a++
  103. c.value
  104. })
  105. }