小编Mau*_*tro的帖子

重新解释将数组从string转换为int

我想在int数组中重新解释一个字符串,其中每个int根据处理器架构负责4或8个字符.

有没有办法以相对便宜的方式实现这一目标?我试过这个,但似乎没有在一个int中重新解释4个字符

string text = "abcdabcdefghefgh";

unsafe
{
    fixed( char* charPointer = text )
    {
        Int32* intPointer = (Int32*)charPointer;

        for( int index = 0; index < text.Length / 4; index++ )
        {
            Console.WriteLine( intPointer[ index ] );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

解决方案:(根据您的需要更改Int64或Int32)

string text = "abcdabcdefghefgh";

unsafe
{
    fixed( char* charPointer = text )
    {
            Int64* intPointer = (Int64*)charPointer;
            int conversionFactor = sizeof( Int64 ) / sizeof( char );

            int index = 0;
            for(index = 0; index < text.Length / conversionFactor; …
Run Code Online (Sandbox Code Playgroud)

c# arrays casting

7
推荐指数
1
解决办法
299
查看次数

各种列表初始化和填充技术的性能差异

我试图找出在构造函数中设置列表的容量是否可以使使用List<T>(IEnumerable<T>)vs List<T>()+之间已经可以忽略不计的性能差异变平AddRange(IEnumerable<T>)

我发现设置的能力之前,AddRange()实际上导致大致相同的性能与初始集合构建的名单。

但还有更多。如果你使用Add()而不是AddRange()?出于某种原因,性能似乎提高了 32%

那么如果我在Add()不使用初始容量初始化列表的构造函数的情况下使用呢?看起来性能比之前的 Add() 方法差,但仍然比AddRange()方法好:性能提升了 26%。

这很奇怪,让我怀疑我的测试是否有效;所以我发布了我所做的测试(在没有调试器的情况下以发布模式运行)。

有人可以证实这一点吗?

int items = 100000;
int cycles = 10000;

var collectionToCopy = Enumerable.Range( 0, items );

var sw0 = new Stopwatch();
sw0.Start();
for( int i = 0; i < cycles; i++ )
{
    List<int> list = new List<int>( collectionToCopy );
}
sw0.Stop();
Console.WriteLine( sw0.ElapsedMilliseconds );

var sw1 …
Run Code Online (Sandbox Code Playgroud)

c# performance list

5
推荐指数
1
解决办法
750
查看次数

C#收益率回报表现

使用yield return语法的方法后面的底层集合保留了多少空间当我在其上执行ToList()时?如果与我创建具有预定义容量的列表的标准方法相比,它有可能重新分配并因此降低性能?

这两种情况:

    public IEnumerable<T> GetList1()
    {
        foreach( var item in collection )
            yield return item.Property;
    }

    public IEnumerable<T> GetList2()
    {
        List<T> outputList = new List<T>( collection.Count() );
        foreach( var item in collection )
            outputList.Add( item.Property );

        return outputList;
    }
Run Code Online (Sandbox Code Playgroud)

c# memory yield return

2
推荐指数
2
解决办法
5388
查看次数

标签 统计

c# ×3

arrays ×1

casting ×1

list ×1

memory ×1

performance ×1

return ×1

yield ×1