0

I defined custom annotation(DataAttribute) like the below. And I have to call checkMaxLength() many times, over 10,000 times. (also toolType, reportTitle and validLength also)

What I'd like to ask is..

I think a) is right(or general) usage of custom annotation. but If I call checkMaxLength over 10,000 times(, and maxLength is always 4000), It's not good for performance compared with b).

What do you think of case b)?? Is this right way to use custom data annotation?

a)
@DataAttribute(toolType = DataTooltype.CustomDateTime, reportTitle = "DateTime", maxLength = 4000, validLength = 4000, pollutedLength = 100)
public class DateTimeData {
    public boolean checkMaxLength(int length) {
        if (DataAnnotationUtil.maxLength(this) < length)
            return false;
        return true;
    }
}


b)
@DataAttribute(toolType = DataTooltype.CustomDateTime, reportTitle = "DateTime", maxLength = 4000, validLength = 4000, pollutedLength = 100)
public class DateTimeData {

    public int maxLength;

    public Email() {
        this.maxLength = DataAnnotationUtil.maxLength(this);
    }

    public boolean checkMaxLength(int length) {
        if (this.maxLength < length)
            return false;
        return true;
    }
}
4

1 回答 1

1

Annotations have no impact on the performance of a method execution. If your question is about DataAnnotationUtil.maxLength(this) it’s obviously more efficient to call it once in the constructor instead of every method invocation. But since annotations are static class data it is even more efficient to call it once per class. Since your method wants this as parameter I don’t know whether it works in a static context, but you don’t need it anyway:

@DataAttribute(toolType = DataTooltype.CustomDateTime, reportTitle = "DateTime", maxLength = 4000, validLength = 4000, pollutedLength = 100)
public class DateTimeData {

    public static final int MAX_LENGTH = DateTimeData.class.getAnnotation(DataAttribute.class).maxLength();

    public DateTimeData() {
    }

    public boolean checkMaxLength(int length) {
        return length < MAX_LENGTH;
    }
}

But it’s even easier as you don’t need any runtime operation at all. MAX_LENGTH is a compile time constant (all annotation values are) so you may declared it inside the class as a constant and let the annotation reference it. Then you don’t need to process the annotation:

@DataAttribute(toolType = DataTooltype.CustomDateTime, reportTitle = "DateTime",
// note the reference here, it’s still a single point of declaration:
maxLength = DateTimeData.MAX_LENGTH, validLength = 4000, pollutedLength = 100)
public class DateTimeData {

    public static final int MAX_LENGTH = 4000;

    public DateTimeData() {
    }

    public boolean checkMaxLength(int length) {
        return length < MAX_LENGTH;
    }
}
于 2013-09-12T07:49:28.310 回答