简体   繁体   中英

Using of Array of chars (char[]) instead of strings in c#

There is no such concept as string in C language, right? So, i'm wondering: would it give any memory saving advantages to use array of chars instead of string in modern languages, as C# for example.

In Python, if I'm understanding you correctly, the answer is "it depends". (I'm using python out of convenience, you said "any modern language")

I made a function that creates a character array of the alphabet, and another that creates a string of the alphabet. Then ran them each 1 million times.

The character array took about 1.7 seconds, compared to the string array's .5 seconds.

"Maybe it's an overhead thing?" you might ask.
Fine: I initialized them globally, then ran an iteration of each one through a loop (1 million times), setting some variable to the current letter.
7.7 seconds for the character array vs 9 seconds for the string.

"What if you're looking for a particular element?"
I ran through each variable to see if 'z' was in the elements. char array took 1.8 seconds vs the strings 0.4 seconds.

"That's interesting, maybe it's just an assignment thing?"
My last test is to just iterate through without assigning anything. Again, the char array is faster with 3.9 seconds vs the 5.3 seconds of the string iteration.

So it seems that Strings are faster for initial creation and searching (I also assume sorting, but I'm not about to write a sorting function to find out), while character arrays are faster for iterative events (for each in array/string).

Hope this helps.
PS - the code for my first test class:

#!/usr/bin/env python
import dis
import time

def char_func():
        my_c_var = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
        #print my_c_var

def stri_func():
        my_s_var = "abcdefghijklmnopqrstuvwxyz"
        #print my_s_var

start_time = time.time()
for i in range(1000000):
        char_func()
print("--- %s seconds ---" % (time.time() - start_time))

start_time = time.time()
for i in range(1000000):
        stri_func()
print("--- %s seconds ---" % (time.time() - start_time))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM