Skip to content
Prev 18254 / 63424 Next

performance of nchar

Hi,
    Is nchar function knowingly slow in R? I'm doing some string 
formatting that requires multiple call to nchar, and nchar seems to be 
very slow.

Experiment 1, pass nchar inside sprintf, and it takes 0.7 seconds
 > system.time(for (i in 1:10000)
+ str = sprintf('0005%020d', nchar(op))
+ )[3]
[1] 0.7

Experiment 2, get the length of op separately using nchar, and then pass 
the value to sprintf.
 > len = nchar(op)
 > system.time(for (i in 1:10000)
+ str = sprintf('0005%020d', len)
+ )[3]
[1] 0.03

Experiment 3, time nchar for 10000 iterations
 > system.time(for (i in 1:10000)
+ nchar(op)
+ )[3]
[1] 0.66

Is there any faster way of getting the length of string in R?

Thank you in advance for your help!


Sincerely,
Jennifer