Solved

String.charAt(index)  Vs String.toCharArray()[index]

Posted on 2004-09-06
10
2,144 Views
Last Modified: 2008-01-09
Hello All,

Which do you think is better operation, so that it increases the performance of method

String str="Hello World";
int len=str.length();
for(int i=0;i<len;i++)
{
        char c=str.charAt(i);
}

char charArray[]=str.toCharAray();

for(int i=0;i<len;i++)
{
        char c=charArray[i];
}
0
Comment
Question by:sudhakar_koundinya
  • 2
  • 2
  • 2
  • +4
10 Comments
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
The best thing is to time it, is it not? Probably the first
0
 
LVL 5

Expert Comment

by:TrekkyLeaper
Comment Utility
charAt is the most efficient. The toCharArray method is forced to allocate a new array to store the characters to create a disconnected copy of the array.
0
 
LVL 3

Expert Comment

by:sbockelman
Comment Utility
Why, are you having a performance issue?

Don't optimize now!  Wait until you find out if you even need to optimize, then profile the application to see where to optimize.  The difference between the 2 alternatives shown is probably so minimal, that even the time to read my post about it was a waste of your time and client's money.

But, if it is found to be the bottleneck method, then...always let the computer tell you which way is better by timing and profiling.  And sometimes, this kind of micro-optimization won't help anyway and you'll need to completely redesign a component or algorithm to resolve the issue.

But, for curiosity sake, please let me know the timings you get for the two methods.  
I'd like to see what the difference is.  Who knows I might need to speed up some text parsing some day.
0
 
LVL 6

Expert Comment

by:expertmb
Comment Utility
char c=str.charAt(i);

is fast compared to

char charArray[]=str.toCharAray();
char c=charArray[i];

first one has array already.
second one from string you are converting to array then accessing
however after converting to array both are same.
0
 
LVL 14

Author Comment

by:sudhakar_koundinya
Comment Utility
Hello Friends,

Thanks for ur inputs


My perception is different.

I agree for smaller strings charAt function may be fast. But when coming to big strings, I think the scenario is different. Because when I see the code for string last night I have found that toCharArray uses function System.arraycopy. We know System.arraycopy(I think it is native call) is faster.

So when we use for loop based operations on String, we are directly moving to index for char array whereas we need to call the function for charAt. So for Bigger strings calling the function multiple times may reduce the performance of the method.

What do you say??

Thanks
Sudhakar


For testing the performance I used following program


class BiggerStringTest
{
      public static void main(String[] args)
      {
            StringBuffer sb=new StringBuffer();
            int n=Integer.parseInt(args[0]);
            for(int i=0;i<n;i++)
            {
                  sb.append('*');
            }
            String str=sb.toString();
            char array[]=str.toCharArray();
            for(int j=0;j<10;j++)
            {
            
            long start=System.currentTimeMillis() ;
            for(int i=0;i<n;i++)
            {
                  if(str.charAt(i)=='A')
                  {
                        //do some thing
                  }
            }

            long end=System.currentTimeMillis() ;
            System.err.println("charAt :"+(end-start));

            
            start=System.currentTimeMillis() ;
            for(int i=0;i<n;i++)
            {
                  if(array[i]=='A')
                  {
                        //do some thing
                  }
            }

            end=System.currentTimeMillis() ;
            System.err.println("char Array : "+(end-start));

      }
      }
}

0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 6

Assisted Solution

by:expertmb
expertmb earned 20 total points
Comment Utility
>>So for Bigger strings calling the function multiple times may reduce the performance of the method.
accessing the array using index is faster. i said this one in one of your previous question also.

0
 
LVL 7

Assisted Solution

by:grim_toaster
grim_toaster earned 20 total points
Comment Utility
Your performance test is biased.  To make it fairer you would need to do the array conversion more often, as in change to the following:

start=System.currentTimeMillis() ;
char array[]=str.toCharArray();
          for(int i=0;i<n;i++) {
               if(array[i]=='A')

There will be a point where the string gets so long that the processing of it will be faster to do the array conversion instead of the charAt.  Although the point will be different on every machine (and you may never get when...).  The reason for this is available if you look at the source code for the String class, the charAt method has additional boundary condition checks:

        if ((index < 0) || (index >= count)) {
            throw new StringIndexOutOfBoundsException(index);
        }

Which would be completely removed if you are accessing a local copy of the array.  However, I would be very surprised if you ever actually noticed any difference, and the figures will be very biased to what other processes are running (i.e. virus checkers).  The best bet would be to profile (I believe mentioned previously), using CPU time (as opposed to elapsed time), to get exact figures.  
0
 
LVL 24

Expert Comment

by:sciuriware
Comment Utility
sudhakar_koundinya, are you gonna write a book from the answers on all your performance
questions? In that case you just CAN'T use our answers.
If such a report is not based on extensive timing tests by yourself on verious platforms and
with a variety of data sets, it will be wiped away by any critic.
And if this is for your boss, he/she will surely ask a specialist to critisize it.
;JOOP!
0
 
LVL 14

Author Comment

by:sudhakar_koundinya
Comment Utility
>>are you gonna write a book from the answers on all your performance questions?

No My Dear,

Actually we are facing severe performance problems with our current application. And also this is not at all a design Issue. Because that is the only way currently we have as we totally depend on third party API (Apache Slide and Apache HttpClient) - and that API was finalised by both our team and client team after extensive R & D only.

I am not only doing these tests, both client team and our team are doing investigation on increasing the performance of API

thanks
sudhakar
0
 
LVL 3

Accepted Solution

by:
sbockelman earned 35 total points
Comment Utility
>> Actually we are facing severe performance problems with our current application

Have you tried something like Quest JProbe (or an open source alternative such as JMeter) to find out WHERE you should be optimizing?

I have led performance optimization efforts after-the-fact on several occasions;  I was sort of the de facto "performance tuning guy" at my last consulting company.

The effort can be very challenging; sometimes frustrating and sometimes fun.

What I have found is that it is almost always a waste of time to tune some little method here or loop there when the response times are truly horrible.  Often, the solution requires some serious creative thinking and some partial redesign.

What kind of application are you trying to tune?  
Sounds like it must be a content management application, given the use of Slide.

My last major optimization effort was for a Documentum WDK-based application.

What we found was that for some features, the API methods exposed by the framework seduced users into writing loops where methods called in the loop were making additional database calls (under the covers).  

By circumventing the DCTM API and going directly against the database, in some cases, we were able to improve performance by orders of magnitude you would not believe (one 'report' screen went from 10-15 minutes to load down to 17 seconds!)

We also found that some operations were obtaining exclusive locks in the backing database (SQL Server in that case).  Because the version of SQL Server being used was locking entire PAGES and sometimes TABLES even for read operations, we had to reconfigure the default transaction isolation level for several operations to allow for "dirty reads", which would pose no problem for our application, but may not be appropriate for yours.

Finally, poor session management and thread-safety concerns had led to some inadvertant or uncessecary synchronization with some types of requests being served serialy instead of in parallel.

SO, I would encourage you to proceed via a thorough analysis of the application's runtime characteristics.  Once you know what is slow, then you can begin to investigate the cause, and finally...possibly recommend and implement a solution.

Saving < 2 milliseconds per character-access is probably not going to solve the larger issues.

Good luck!




0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
hash value 2 38
mapAB Challlenge 35 84
eclipse package explorer vs project explorer view 2 27
recursion example 16 66
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now