-
Notifications
You must be signed in to change notification settings - Fork 0
/
caching.go
109 lines (88 loc) · 1.8 KB
/
caching.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// Package caching provides code to show why Data Oriented Design matters. How
// data layouts matter more to performance than algorithm efficiency.
package caching
import "fmt"
// Create a square matrix of 16,777,216 bytes.
const (
rows = 4 * 1024
cols = 4 * 1024
)
// A data represents a data node for our linked list.
type data struct {
v byte
p *data
}
var (
// matrix represents a matrix with a large number of
// columns per row.
matrix [rows][cols]byte
// list points to the head of the list.
list *data
)
func init() {
var last *data
// Create a link list with the same number of elements.
for row := 0; row < rows; row++ {
for col := 0; col < cols; col++ {
// Create a new node and link it in.
var d data
if list == nil {
list = &d
}
if last != nil {
last.p = &d
}
last = &d
// Add a value to all even elements.
if row%2 == 0 {
matrix[row][col] = 0xFF
d.v = 0xFF
}
}
}
// Count the number of elements in the link list.
var ctr int
d := list
for d != nil {
ctr++
d = d.p
}
fmt.Println("Elements in the link list", ctr)
fmt.Println("Elements in the matrix", rows*cols)
}
// LinkedListTraverse traverses the linked list linearly.
func LinkedListTraverse() int {
var ctr int
d := list
for d != nil {
if d.v == 0xFF {
ctr++
}
d = d.p
}
return ctr
}
// ColumnTraverse traverses the matrix linearly down each column.
func ColumnTraverse() int {
var ctr int
for col := 0; col < cols; col++ {
for row := 0; row < rows; row++ {
if matrix[row][col] == 0xFF {
ctr++
}
}
}
return ctr
}
// RowTraverse traverses the matrix linearly down each row.
func RowTraverse() int {
var ctr int
for row := 0; row < rows; row++ {
for col := 0; col < cols; col++ {
if matrix[row][col] == 0xFF {
ctr++
}
}
}
return ctr
}