Created
September 1, 2014 17:00
-
-
Save jeroen/498223c20d7e0416c169 to your computer and use it in GitHub Desktop.
Performance comparison of deparsing character vectors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Version 1 | |
deparse_vector1 <- function(x) { | |
stopifnot(is.character(x)) | |
vapply(x, deparse, character(1), USE.NAMES=FALSE) | |
} | |
# Version 2 | |
deparse_vector2 <- function(x) { | |
stopifnot(is.character(x)) | |
if(!length(x)) return(x) | |
x <- gsub("\\", "\\\\", x, fixed=TRUE) | |
x <- gsub("\"", "\\\"", x, fixed=TRUE) | |
x <- gsub("\n", "\\n", x, fixed=TRUE) | |
x <- gsub("\r", "\\r", x, fixed=TRUE) | |
x <- gsub("\t", "\\t", x, fixed=TRUE) | |
x <- gsub("\b", "\\b", x, fixed=TRUE) | |
x <- gsub("\f", "\\f", x, fixed=TRUE) | |
paste0("\"", x, "\"") | |
} | |
# Create vector with random trings | |
mychars <- c(letters, " ", '"', "\\", "\t", "\n", "\r", "'", "/", "#", "$"); | |
createstring <- function(length){ | |
paste(mychars[ceiling(runif(length, 0, length(mychars)))], collapse="") | |
} | |
strings <- vapply(rep(1000, 10000), createstring, character(1), USE.NAMES=FALSE) | |
# Test performance | |
system.time(out1 <- deparse_vector1(strings)) | |
system.time(out2 <- deparse_vector2(strings)) | |
# Verify that escape was correct | |
orig1 <- vapply(out1, function(x){parse(text=x)[[1]]}, character(1), USE.NAMES=FALSE) | |
orig2 <- vapply(out2, function(x){parse(text=x)[[1]]}, character(1), USE.NAMES=FALSE) | |
identical(strings, orig1) | |
identical(strings, orig2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment