The current state of generics in Delphi

 

To avoid duplication of generated code, the compiler builders of Embarcadero have done a nice job. They introduced new instrinsics like IsManagedType, GetTypeKind and IsConstantType (see this Stackoverflow answer), so they could make a function like the following generate a call to the exact function for the parametric type directly. This means that the code below "runs" completely inside the compiler, even the code in the called InternalAddMRef and similar dispatching routines.

function TList.Add(const Value: T): Integer;
begin
if
IsManagedType(T) then
begin
if
(SizeOf(T) = SizeOf(Pointer)) and (GetTypeKind(T) <> tkRecord) then
Result := FListHelper.InternalAddMRef(Value, GetTypeKind(T))
else if GetTypeKind(T) = TTypeKind.tkVariant then
Result := FListHelper.InternalAddVariant(Value)
else
Result := FListHelper.InternalAddManaged(Value);
end else
case
SizeOf(T) of
1: Result := FListHelper.InternalAdd1(Value);
2: Result := FListHelper.InternalAdd2(Value);
4: Result := FListHelper.InternalAdd4(Value);
8: Result := FListHelper.InternalAdd8(Value);
else
Result := FListHelper.InternalAddN(Value);
end;
end;

That, in its turn, means that if you code something like:

var
List: TList<string>;
begin
List := TList<string>>.Create;
List.Add('Hello');

then

List.Add('Hello');

is in fact directly compiled as

List.FListHelper.DoAddString('Hello');

i.e. TList.Add does not have any runtime code at all, the result of "calling" it (see above) is the generation of a direct call to the DoAddString function. That is a simple method, not generic, not virtual or dynamic, like all the other methods of TListHelper, so the unused functions can be eliminated by the linker. This also means there is hardly any duplication of generated code anymore, i.e. if another part of the same executable also uses TList<string>.Add it will use the same function.

No code duplication?

Well, this means that if the class is coded like above, there is no unnecessary duplication of generated code anymore. That is cool and can probably reduce the expected bloat caused by using generics.

But it also means that it greatly reduces one of the advantages associated with generics: no unnecessary duplication of source code. You write a routine once, and only the type it works on is parametrized. The compiler takes care of generating code for each used routine and parametric type.

But then you still get the dreaded bloat. So you either duplicate a lot of source code (take a look at the code of TListHelper in System.Generics.Collections to see what I mean; for example, the functions DoAddWideString, DoAddDynArray, DoAddInterface and DoAddString contain exactly the same code, except for the lines where FItems^ is cast each to a different pointer type), which is almost as much work as writing a separate TList for each type, or you use the naïve approach, writing code only once, as generics should actually be used. But then you could get bloat again, i.e. it is well possible that the same routine gets generated multiple times, in different units of the same executable.

What to do?

There is not much we can do, except to emphatically ask Embarcadero to put the kind of logic that was implemented in TList<T> and other generic classes to avoid duplication of generated code, in the compiler and linker, so we don't have to write huge helper classes nor get the bloat.

In the meantime, you can do what Embarcadero did: if your class is used a lot for many different types, do a lot of "copy and paste generics". Otherwise, if you only have to deal with a few types and in a few places, simply use the naïve approach. Or you use a hybrid approach, using the intrinsics mentioned above and implementing the most used helper functions for the types you need most.

Let's hope they get a lot of requests and implement these things in the compiler and linker, like other languages with generics, e.g. C# or C++, do.

Rudy Velthuis

The current state of generics in Delphi( 转载)的更多相关文章

  1. “Operation is not valid due to the current state of the object.”

    将Repeater单页显示的2000条数据一次性提交的时候出现这个错误: Operation is not valid due to the current state of the object. ...

  2. 关于 error: Operation is not valid due to the current state of the object。

    今天碰到一个特别的异常. Operation is not valid due to the current state of the object. at System.Web.HttpValueC ...

  3. Error occurred in deployment step 'Add Solution': Operation is not valid due to the current state of the object.

    Sharepoint 部署的时候出现一个错误 Error occurred in deployment step 'Add Solution': Operation is not valid due ...

  4. Operation is not valid due to the current state of the object.

    今天遇到一个asp.net的草郁闷的问题,看下截图 狂晕啊,在google上狂搜了一下,好在已经有大侠也遇到过这个问题了,先看下别人的解决办法吧 Operation is not valid due ...

  5. Unable to boot device in current state: Creating

    安装完xcode6.1后,将其改名为Xcode6.1.app,再移动个位置,启动模拟器,问题来了: Unable to boot device in current state: Creating 解 ...

  6. Cannot attach medium 'D:\program\VirtualBox\VBoxGuestAdditions.iso' {}: medium is already associated with the current state of machine uuid {}返回 代码: VBOX_E_OBJECT_IN_USE (0x80BB000C)

    详细的错误信息如下: Cannot attach medium 'D:\program\VirtualBox\VBoxGuestAdditions.iso' {83b35b10-8fa2-4b81-8 ...

  7. vs问题解决:an operation is not legal in the current state

    debug时弹出提示框:内容有:an operation is not legal in the current state 解决方案: Go to Tools > Options > D ...

  8. GridView Postback后出错Operation is not valid due to the current state of the object.

    一.问题起因 最近项目中有一页面第一次search后正常,但是再次点击其它任何按钮都会报错,亦即postback后页面有问题,经检查是由于页面有一GridView且数据量极大,记录大概有上千条,这儿解 ...

  9. 前端 vue单页面应用刷新网页后vuex的state数据丢失的解决方案(转载)

    最近接手了一个项目,前端后端都要做,之前一直在做服务端的语言.框架和环境,前端啥都不会啊. 突然需要前端编程,两天速成了JS和VUE框架,可惜还是个半吊子.然后遇到了一个困扰了一整天的问题.一直调试都 ...

随机推荐

  1. 浅析负载均衡的6种算法,Ngnix的5种算法。

    浅析负载均衡的6种算法,Ngnix的5种算法.浮生偷闲百家号03-21 10:06关注内容导读其实际效果越来越接近于平均分配调用量到后端的每一台服务器,也就是轮询的结果.源地址哈希的思想是根据获取客 ...

  2. Android开发 assets目录

    Android资源文件分类: Android资源文件大致可以分为两种: 第一种是res目录下存放的可编译的资源文件: 这种资源文件系统会在R.Java里面自动生成该资源文件的ID,所以访问这种资源文件 ...

  3. PHP生成HTML静态页面。

    function Generate(){ $html = '<!DOCTYPE html><html lang="en"><head> < ...

  4. log4j配置后行号乱码显示为?问号

    debug="true"  classpathref="accrual.path" > 首发于 http://blog.xfuse.cn 参考文档 htt ...

  5. idea导入项目

    1. 2.导入项目 3.右键项目选择web 4.编辑添加tomcat 5.添加jar.包 6. 7.右键put into 8.安装tomcat 9.引入tomcat 10.把项目布署到tomcat

  6. Linux常用基础操作命令大全(超实用精心整理)

    相信大家都对黑客那种只用命令行对电脑操作的风格惊呆了,其实你也可以做到.linux是一款不同于windows的操作系统,而且它是黑客.渗透人员.运维人员等等必会的.如果你想学习,小编下面整理的命令将会 ...

  7. html背景图星际导航图练习

    html <body>         <div class="box1">            <div></div>      ...

  8. extJs学习的资源

    http://www.qeefee.com/zt-extjs   Ext JS 6 入门学习资料大全(2016-12-14)   cddnExtJS学习:http://blog.csdn.net/co ...

  9. Android Studio修改项目中整体包名

    莫名的需求,要把之前的apk分成三个不同的apk,还要在应用市场能够上线,麻麻滴这样一听那还不要各个apk包的包名不同以及apk签名文件也不同嘛(签名文件一般也用不同,为防止上线冲突嘛).所以就亲自尝 ...

  10. java基础-- 之类型转换 和 一些运算符

    ---   首先   看一个 Scanner  类 import java.util.Scanner; public class TestScanner { public static void ma ...