简体   繁体   English

在c#中使用字符数组(char [])而不是字符串

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

There is no such concept as string in C language, right? C语言中没有字符串这样的概念,对吧? 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. 所以,我想知道:在现代语言中使用字符数组而不是字符串可以节省任何内存优势,例如C#。

In Python, if I'm understanding you correctly, the answer is "it depends". 在Python中,如果我正确理解你,答案是“它取决于”。 (I'm using python out of convenience, you said "any modern language") (我在方便时使用python,你说“任何现代语言”)

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. 然后每100万次运行它们。

The character array took about 1.7 seconds, compared to the string array's .5 seconds. 与字符串数组的.5秒相比,字符数组花了大约1.7秒。

"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. 好的:我在全局初始化它们,然后通过循环(100万次)运行每个迭代,将一些变量设置为当前字母。
7.7 seconds for the character array vs 9 seconds for the string. 字符数组为7.7秒,字符串为9秒。

"What if you're looking for a particular element?" “如果你正在寻找一个特定元素怎么办?”
I ran through each variable to see if 'z' was in the elements. 我浏览了每个变量,看看'z'是否在元素中。 char array took 1.8 seconds vs the strings 0.4 seconds. char数组花了1.8秒对弦0.4秒。

"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. 同样,char数组比3.9秒的字符串迭代速度快3.9秒。

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). 所以看起来Strings在初始创建和搜索方面更快(我也假设排序,但我不打算编写排序函数来查找),而字符数组对于迭代事件更快(对于数组/字符串中的每一个) 。

Hope this helps. 希望这可以帮助。
PS - the code for my first test class: PS - 我的第一个测试类的代码:

#!/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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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