【48期】盤點Netty面試常問考點:什么是 Netty 的零拷貝?
閱讀本文大概需要 4.5 分鐘。
來自:my.oschina.net/plucury/blog/192577
"Zero-copy" describes computer operations in which the CPU does not perform the task of copying data from one memory area to another.






private?int?readerIndex;
private?int?writerIndex;
private?ChannelBuffer[]?components;
private?int[]?indices;
private?int?lastAccessedComponentId;
/**
?*?Setup?this?ChannelBuffer?from?the?list
?*/
private?void?setComponents(List?newComponents) ?{
????assert?!newComponents.isEmpty();
????//?Clear?the?cache.
????lastAccessedComponentId?=?0;
????//?Build?the?component?array.
????components?=?new?ChannelBuffer[newComponents.size()];
????for?(int?i?=?0;?i?????????ChannelBuffer?c?=?newComponents.get(i);
????????if?(c.order()?!=?order())?{
????????????throw?new?IllegalArgumentException(
????????????????????"All?buffers?must?have?the?same?endianness.");
????????}
????????assert?c.readerIndex()?==?0;
????????assert?c.writerIndex()?==?c.capacity();
????????components[i]?=?c;
????}
????//?Build?the?component?lookup?table.
????indices?=?new?int[components.length?+?1];
????indices[0]?=?0;
????for?(int?i?=?1;?i?<=?components.length;?i?++)?{
????????indices[i]?=?indices[i?-?1]?+?components[i?-?1].capacity();
????}
????//?Reset?the?indexes.
????setIndex(0,?capacity());
}
public?byte?getByte(int?index)?{
????int?componentId?=?componentId(index);
????return?components[componentId].getByte(index?-?indices[componentId]);
}
private?int?componentId(int?index)?{
????int?lastComponentId?=?lastAccessedComponentId;
????if?(index?>=?indices[lastComponentId])?{
????????if?(index?1])?{
????????????return?lastComponentId;
????????}
????????//?Search?right
????????for?(int?i?=?lastComponentId?+?1;?i?????????????if?(index?1])?{
????????????????lastAccessedComponentId?=?i;
????????????????return?i;
????????????}
????????}
????}?else?{
????????//?Search?left
????????for?(int?i?=?lastComponentId?-?1;?i?>=?0;?i?--)?{
????????????if?(index?>=?indices[i])?{
????????????????lastAccessedComponentId?=?i;
????????????????return?i;
????????????}
????????}
????}
????throw?new?IndexOutOfBoundsException("Invalid?index:?"?+?index?+?",?maximum:?"?+?indices.length);
}
推薦閱讀:
【46期】盤點那些必問的數(shù)據(jù)結構算法題之快速排序
【45期】盤點那些必問的數(shù)據(jù)結構算法題之基礎排序
微信掃描二維碼,關注我的公眾號
朕已閱?
評論
圖片
表情

