Skip to content

Commit 21fa19f

Browse files
committed
Added some tips on memory and speedy use of names via environments (due to Joseph Adler)
1 parent 9ef87f5 commit 21fa19f

File tree

1 file changed

+39
-4
lines changed

1 file changed

+39
-4
lines changed

CodeTricks.md

+39-4
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@ Matlab
1414
* Use the matlab profiler
1515

1616
R
17-
-
18-
* R profiler: Rprof (functionalize your code first)
19-
* sapply instead of for loops
17+
-----
2018

19+
* R profiler: Rprof (functionalize your code first)
20+
* sapply instead of for loops
2121

2222

2323
Did you know, in R:
@@ -36,10 +36,34 @@ and `a^2 ` is slower than `a*a`.
3636

3737
Radford Neal [pointed this out](http://radfordneal.wordpress.com/2010/08/19/speeding-up-parentheses-and-lots-more-in-r/) in R-2.11.1, try testing in R 2.14.1 first.
3838

39-
Also, although many matrix operations can be performed on `data.frame`, they are _much_ faster when performed on `matrix` data types[^dfmat].
39+
## Names and speed
40+
41+
Although many matrix operations can be performed on `data.frame`, they are _much_ faster when performed on `matrix` data types[^dfmat].
4042

4143
[^dfmat]: need a small example of this
4244

45+
Accesssing arrays via index is faster than by name, but using names can make for more readable code.
46+
To achieve fast access and still use names, one can construct an environment that uses a hash table for lookup
47+
48+
```R
49+
labeled.environment <- function(n) {
50+
e <- new.env(hash=TRUE,size=n)
51+
from <- "0123456789"
52+
to <- "ABCDEFGHIJ"
53+
for (i in 1:n) {
54+
assign(x=chartr(from,to,i), value=i, envir=e)
55+
}
56+
e
57+
}
58+
e.20 <- labeled.environment(20)
59+
60+
## Access via
61+
e.20[["B"]]
62+
get("BH", env=e.20)
63+
```
64+
65+
This tip is from [Joseph Adler](http://broadcast.oreilly.com/2010/03/lookup-performance-in-r.html)
66+
4367

4468
## Compiling code
4569

@@ -48,3 +72,14 @@ As of `R` 2.13, the `compiler` package lets you compile code into byte for faste
4872
`compiled.function <- cmpfun(orig.function)`
4973

5074
A demonstration [here](http://dirk.eddelbuettel.com/blog/2011/04/12/) shows that it speeds some basic functions up about 4X.
75+
76+
## Memory
77+
78+
* preallocate memory
79+
80+
### manage memory
81+
82+
* free up space and display stats with `gc()`
83+
* check memory use by `x` using `object.size(x)`
84+
* use `memory.profile()`
85+
* use `mem.limits()` to get/set memory limits

0 commit comments

Comments
 (0)