代码改变世界

ArcObjects拾遗之三——创建点要素

2012-05-08 19:18 贼寇在何方 阅读(...) 评论(...) 编辑 收藏

比起之前创建要素类的繁杂步骤,在已有要素类的情况下创建要素,就相对简单多了的:

// 创建点要素
static void CreateFeature(IFeatureClass featureClass, IPoint point)
{
    var feature = featureClass.CreateFeature();
    feature.Shape = point;
    feature.Store();
}

 

这个方法简单,但是缺点也很明显:每一次创建要素都要执行一遍Store,对硬盘进行一次写入。这在批量数据写入时劣势相当明显。
所以我们引入一个FeatureBuffer:

static void CreateFeaturesWithBuffer(IFeatureClass featureClass, IPoint[] points)
{
    var featureCursor = featureClass.Insert(true);
    foreach (var point in points)
    {
        var featureBuffer = featureClass.CreateFeatureBuffer();
        featureBuffer.Shape = point;
        featureCursor.InsertFeature(featureBuffer);
    }
    featureCursor.Flush();

    Marshal.ReleaseComObject(featureCursor);
}

这次传入的第二个参数是一个点的数组,再给出CreateFeature的复数版本:

static void CreateFeatures(IFeatureClass featureClass, IPoint[] points)
{
    foreach (var point in points)
    {
        var feature = featureClass.CreateFeature();
        feature.Shape = point;
        feature.Store();
    }
}

 

既然说FeatureBuffer在批量数据下有优势,那就跑一回试试吧。
来一个测试执行时间的方法:

static void GetExecuteTime(Action<IFeatureClass, IPoint[]> func, IFeatureClass featureClass, IPoint[] points)
{
    var sw = new Stopwatch();
    sw.Start();
    func(featureClass, points);
    sw.Stop();

    Console.WriteLine(func.Method.Name);
    Console.WriteLine("执行时间(s) : " + sw.Elapsed.ToString());
    Console.WriteLine("平均插入一个要素时间(s) : " + sw.Elapsed.TotalSeconds / points.Length);
    Console.WriteLine();
}

测试结果,在插入481个点要素的情况下,不使用缓存消耗的时间约是使用的160倍。
因此,在批量创建要素是,强烈建议使用FeatureBuffer而不是Feature