From lai at lindaspaces.com  Tue Oct 25 18:54:12 2005
From: lai at lindaspaces.com (Jennifer Lai)
Date: Tue, 25 Oct 2005 12:54:12 -0400
Subject: [Rd] performance of nchar
Message-ID: <435E6334.5050003@lindaspaces.com>

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



[Rd] performance of nchar
Jennifer Lai